Proper error handling is a crucial part of any production app, even if it isn’t the most exciting thing.
Nuxt 3 comes with the NuxtErrorBoundary
component which makes handling client-side errors a breeze:
<NuxtErrorBoundary><!-- Put components in here --></NuxtErrorBoundary>
Use the error
named slot and the error
object to show an error message to the user:
<template #error="{ error }"><div><p>Oops, it looks like the video player broke :/</p><p>{{ error.message }}</p></div></template>
If we pass the error
object to another method, we can more easily manipulate it in order to resolve our error:
<NuxtErrorBoundary><ImageViewer /><template #error="{ error }"><div><p>Oops, the image viewer isn't working properly!</p><p>{{ error.message }}</p><!-- Pass the error to another method to recover --><p><button @click="recoverFromError(error)">Try again</button></p></div></template></NuxtErrorBoundary>
Use a recoverFromError
function to set the value of the error
ref to null
and re-render the default slot:
const recoverFromError = (error) => {// Try to resolve the error hereerror.value = null;}
In some cases, a more drastic action might be needed, like navigating to a safe page using the navigateTo
utility:
const recoverFromError = async (error) => {// Navigate away first, otherwise we'll get stuck in a loopawait navigateTo('/');error.value = null;};
You can place NuxtErrorBoundary
components around distinct chunks of functionality, like each widget in an admin dashboard, to contain and handle errors in specific ways.
This is better than simply having a generic error message that’s shown no matter what the error is. By isolating errors with NuxtErrorBoundary
we can show more useful error messages and provide better ways of recovering!
Learn more from the docs: https://nuxt.com/docs/api/components/nuxt-error-boundary