JAVASCRIPT
Centralized Error Handling with `onErrorCaptured`
Implement robust error handling in Vue 3 using the `onErrorCaptured` lifecycle hook to catch and manage errors from child components gracefully.
// components/BuggyComponent.vue
<template>
<div style="border: 1px dashed red; padding: 10px; margin-top: 10px;">
<h3>Buggy Component</h3>
<button @click="causeRuntimeError">Cause Runtime Error</button>
<p>Clicking the button will intentionally cause an error.</p>
</div>
</template>
<script setup>
const causeRuntimeError = () => {
// Intentionally cause an error that Vue's error boundary can catch
const obj = undefined;
console.log(obj.property); // This will throw a TypeError: Cannot read properties of undefined (reading 'property')
};
</script>
// App.vue (Parent component - Error Boundary)
<template>
<div style="border: 2px solid #dc3545; padding: 20px;">
<h1>Parent Component (Error Boundary)</h1>
<p v-if="appError" class="error-message">Application Error: {{ appError }}</p>
<template v-if="!appError">
<BuggyComponent />
</template>
<template v-else>
<p>The Buggy Component encountered an error and was hidden.</p>
<button @click="appError = null">Reset Error</button>
</template>
</div>
</template>
<script setup>
import { ref, onErrorCaptured } from 'vue';
import BuggyComponent from './components/BuggyComponent.vue';
const appError = ref(null);
onErrorCaptured((err, instance, info) => {
console.error('Error caught in App.vue (Parent Component):', err.message, instance, info);
appError.value = err.message; // Store the error message
// Returning `false` from onErrorCaptured will prevent the error
// from propagating further up the component tree.
// Returning `true` or nothing allows it to propagate to global handlers.
return false; // Stop propagation here to handle locally
});
</script>
<style>
.error-message {
color: red;
font-weight: bold;
background-color: #f8d7da;
border: 1px solid #f5c6cb;
padding: 10px;
margin-bottom: 10px;
border-radius: 4px;
}
</style>
How it works: This snippet demonstrates how to use Vue 3's `onErrorCaptured` lifecycle hook to create an error boundary. When an error is thrown by a descendant component (e.g., in `BuggyComponent`), `onErrorCaptured` in a parent component (`App.vue` in this case) will catch it. This allows you to gracefully handle errors, display a fallback UI, log the error, and prevent the entire application from crashing. By returning `false` from the hook, you can stop the error from propagating further up the component chain, allowing for localized error recovery.