JAVASCRIPT
Global and Local Error Handling with Vue 3 onErrorCaptured
Implement robust error handling in your Vue 3 applications using the `onErrorCaptured` lifecycle hook to catch and manage errors bubbling up from child components.
<!-- ErrorProneComponent.vue (Child Component) -->
<template>
<div>
<button @click="throwError">Trigger Error</button>
<p>This component might throw an error.</p>
</div>
</template>
<script setup>
function throwError() {
// Simulate an error
throw new Error('Something went wrong in ErrorProneComponent!');
}
</script>
<!-- App.vue (Parent Component) -->
<template>
<div>
<h1>Error Handling Example</h1>
<div class="error-boundary" v-if="componentError">
<p><strong>Caught an error:</strong> {{ componentError }}</p>
<button @click="componentError = null">Reset Error</button>
</div>
<div v-else>
<ErrorProneComponent />
<p>No error currently displayed from child.</p>
</div>
<hr/>
<p>This part of the app is unaffected.</p>
</div>
</template>
<script setup>
import { ref, onErrorCaptured } from 'vue';
import ErrorProneComponent from './ErrorProneComponent.vue'; // Assuming it's in the same directory
const componentError = ref(null);
onErrorCaptured((err, instance, info) => {
console.error('Error captured by onErrorCaptured:', err, instance, info);
componentError.value = err.message;
// Prevent the error from propagating further up the component tree or to global error handler
return false;
});
</script>
<style scoped>
.error-boundary {
border: 2px solid red;
padding: 15px;
background-color: #ffe0e0;
color: red;
margin-bottom: 20px;
}
</style>
How it works: This snippet demonstrates how to implement local error boundaries in Vue 3 using the `onErrorCaptured` lifecycle hook. When an error is thrown in `ErrorProneComponent` (or any of its descendants), `onErrorCaptured` in `App.vue` catches it. It logs the error details, updates a reactive `componentError` state, and crucially, returns `false` to prevent the error from continuing to propagate up the component tree or to the global error handler. This allows the parent component to display a user-friendly error message or a fallback UI, ensuring a more resilient application experience without crashing the entire app.