Nuxt Tip: Handle Client-Side Errors
Michael Hoffmann
@mokkapps
Nuxt will display a generic error page if an error occurs on the client-side. You often don't want to show a fullscreen error page but the error at a specific place in your app. Therefore, Nuxt provides the <NuxtErrorBoundary>
component:
<template>
<NuxtErrorBoundary>
<AnyComponent/>
</NuxtErrorBoundary>
</template>
<NuxtErrorBoundary>
will catch all errors in its default slot.
You can use the #error
slot to display the error to the user. It provides an clearError
function to clear the error and display the children again:
<script setup lang="ts">
const onError = (error: Error) => {
// Here you can try to resolve the error
}
</script>
<template>
<NuxtErrorBoundary @error="onError">
<AnyComponent/>
<template #error="{ error, clearError }">
An error occurred: {{ error.message }}
<button @click="clearError">
Try again
</button>
</template>
</NuxtErrorBoundary>
</template>
error = null
in onError
to clear the error. However, this will re-render the default slot. If you haven't resolve the error completely yet, the error slot will be rendered again, which can lead to an infinite loop.A solution is to navigate to a different page in onError
:<script setup lang="ts">
const recoverFromError = async (error) => {
await navigateTo('/');
error.value = null;
}
</script>
Check out this live example that demonstrates how to handle errors in different contexts: pages, plugins, components and middleware.
If you liked this Vue tip, follow me on BlueSky to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue & Nuxt newsletter :