JAVASCRIPT
Global Error Handling in Vue 3 Component Trees with `onErrorCaptured`
Implement localized error boundaries in Vue 3 applications using `onErrorCaptured` to gracefully manage, display, and report errors within component hierarchies.
<!-- ErrorProneComponent.vue -->
<template>
<button @click="throwError">Click to Throw Error</button>
</template>
<script setup>
const throwError = () => {
throw new Error('Something went wrong in ErrorProneComponent!');
};
</script>
<!-- ParentComponent.vue -->
<template>
<div>
<h1>Parent Component</h1>
<p v-if="error">Error caught: {{ error.message }}</p>
<ErrorProneComponent />
</div>
</template>
<script setup>
import { ref, onErrorCaptured } from 'vue';
import ErrorProneComponent from './ErrorProneComponent.vue';
const error = ref(null);
onErrorCaptured((err, instance, info) => {
error.value = err;
console.error('Caught error:', err, 'from component:', instance, 'info:', info);
// Return false to stop the error from propagating further up the component tree
// return false;
});
</script>
How it works: The `onErrorCaptured` hook in Vue 3's Composition API allows a parent component to intercept errors originating from any of its child components. When an error is thrown in `ErrorProneComponent`, `onErrorCaptured` in `ParentComponent` is invoked, allowing it to log the error, display an error message, or perform other recovery actions. Returning `false` from `onErrorCaptured` prevents the error from propagating to ancestor components, effectively creating an error boundary.