JAVASCRIPT
Global Error Handling in Vue 3 Components with `onErrorCaptured`
Learn to gracefully capture and handle errors that occur within any descendant component using Vue 3's `onErrorCaptured` hook, creating robust error boundaries.
// ErrorBoundary.vue
<template>
<div class="error-boundary">
<template v-if="hasError">
<p>Something went wrong!</p>
<details style="white-space: pre-wrap;">{{ error }}</details>
<button @click="resetError">Try Again</button>
</template>
<template v-else>
<slot></slot>
</template>
</div>
</template>
<script setup>
import { ref, onErrorCaptured } from 'vue';
const hasError = ref(false);
const error = ref(null);
onErrorCaptured((err, instance, info) => {
hasError.value = true;
error.value = err.message + '
' + info; // Log error details
console.error('Captured error:', err, instance, info);
// Return false to stop the error from propagating further up the component tree
return false;
});
const resetError = () => {
hasError.value = false;
error.value = null;
};
</script>
<style scoped>
.error-boundary { border: 2px dashed red; padding: 15px; margin: 10px; background-color: #ffe0e0; }
</style>
// FaultyComponent.vue
<template>
<div>
<button @click="throwError">Trigger Error</button>
<p v-if="message">{{ message }}</p>
</div>
</template>
<script setup>
import { ref } from 'vue';
const message = ref('');
const throwError = () => {
message.value = 'About to explode...';
setTimeout(() => {
throw new Error('An intentional error occurred in FaultyComponent!');
}, 100);
};
</script>
// App.vue
<template>
<h1>App Root</h1>
<ErrorBoundary>
<FaultyComponent />
</ErrorBoundary>
<ErrorBoundary>
<p>This is another section that won't be affected by errors in the above boundary.</p>
<FaultyComponent />
</ErrorBoundary>
<p>Application continues here...</p>
</template>
<script setup>
import ErrorBoundary from './ErrorBoundary.vue';
import FaultyComponent from './FaultyComponent.vue';
</script>
How it works: This snippet demonstrates creating an error boundary component using Vue 3's `onErrorCaptured` lifecycle hook. When `onErrorCaptured` is called in `ErrorBoundary.vue`, it captures any errors thrown by its descendant components (like `FaultyComponent.vue`) during their lifecycle hooks or event handlers. The `hasError` ref is updated, and an error message is displayed, effectively preventing the entire application from crashing and providing a fallback UI. Returning `false` from `onErrorCaptured` stops the error from propagating further up the component tree, localizing the error display.