VUE
Global Error Handling with `onErrorCaptured`
Catch and manage errors globally within your Vue 3 component tree using the `onErrorCaptured` lifecycle hook. Implement robust error boundaries for a better user experience.
// App.vue (Root component or an error boundary component)
<template>
<div>
<h1>Application</h1>
<p v-if="error">An error occurred: {{ error.message }}</p>
<ChildComponent />
</div>
</template>
<script setup>
import { ref, onErrorCaptured } from 'vue';
import ChildComponent from './ChildComponent.vue';
const error = ref(null);
onErrorCaptured((err, instance, info) => {
error.value = err;
console.error('Caught an error in App.vue:', err, info);
// Prevent error from propagating further up the component chain
return false;
});
</script>
// ChildComponent.vue
<template>
<div>
<h2>Child Component</h2>
<button @click="throwError">Trigger Error</button>
<GrandchildComponent />
</div>
</template>
<script setup>
import GrandchildComponent from './GrandchildComponent.vue';
const throwError = () => {
throw new Error('Something went wrong in ChildComponent!');
};
</script>
// GrandchildComponent.vue
<template>
<div>
<h3>Grandchild Component</h3>
<button @click="throwAsyncError">Trigger Async Error</button>
</div>
</template>
<script setup>
const throwAsyncError = () => {
setTimeout(() => {
throw new Error('Async error from GrandchildComponent!');
}, 0);
};
</script>
How it works: This snippet demonstrates how to use Vue 3's `onErrorCaptured` hook to catch errors that occur within a component's subtree. When an error is thrown in `ChildComponent` or `GrandchildComponent`, `onErrorCaptured` in `App.vue` catches it, allowing you to display a user-friendly message or log the error. Returning `false` from the handler prevents the error from propagating further up the component tree. This mechanism provides a powerful way to implement error boundaries and improve application resilience.