JAVASCRIPT
Implementing a Global Error Boundary in Vue 3
Create a robust error boundary component in Vue 3 using the `errorCaptured` lifecycle hook to gracefully catch and display errors from descendant components, improving user experience.
// components/ErrorBoundary.vue
<template>
<slot v-if="!hasError"></slot>
<div v-else class="error-message">
<h2>Something went wrong!</h2>
<p>{{ error.message }}</p>
<button @click="resetError">Try Again</button>
</div>
</template>
<script setup>
import { ref, onErrorCaptured } from 'vue';
const hasError = ref(false);
const error = ref(null);
onErrorCaptured((err, instance, info) => {
console.error('Error caught by error boundary:', err, instance, info);
hasError.value = true;
error.value = err;
// Return false to prevent the error from propagating further up the component tree
return false;
});
const resetError = () => {
hasError.value = false;
error.value = null;
};
</script>
<style scoped>
.error-message {
border: 1px solid red;
padding: 20px;
background-color: #ffeaea;
color: #c00;
text-align: center;
border-radius: 8px;
margin: 20px 0;
}
</style>
// components/BuggyComponent.vue (A component designed to throw an error)
<template>
<div>
<h3>Buggy Component</h3>
<button @click="throwError">Click to Throw Error</button>
</div>
</template>
<script setup>
const throwError = () => {
throw new Error('This is an intentional error from BuggyComponent!');
};
</script>
// App.vue (Parent component using the ErrorBoundary)
<template>
<div>
<h1>Application</h1>
<p>This is the main content.</p>
<ErrorBoundary>
<BuggyComponent />
</ErrorBoundary>
<p>More content below the error boundary.</p>
</div>
</template>
<script setup>
import ErrorBoundary from './components/ErrorBoundary.vue';
import BuggyComponent from './components/BuggyComponent.vue';
</script>
How it works: This snippet demonstrates how to create an 'Error Boundary' component in Vue 3 using the `onErrorCaptured` lifecycle hook. This special hook allows a parent component to capture errors thrown by any of its descendant components. When an error occurs within its slot content, the `ErrorBoundary` component catches it, prevents it from crashing the entire application, and displays a fallback UI with an error message, improving the robustness and user experience of your application. It also provides a way to `resetError` and re-render the child component.