javascript / beginner
Snippet
Component Error Boundary with onErrorCaptured
The onErrorCaptured lifecycle hook registers an error handler that captures errors propagating from descendant components. Returning false stops the error from propagating further up the component hierarchy.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import { ref, onErrorCaptured } from 'vue';export default {setup() {const errorMessage = ref(null);onErrorCaptured((err) => {errorMessage.value = err.message;return false;});return { errorMessage };}};
vue
Breakdown
1
const errorMessage = ref(null);
Creates a reactive variable to store the error message if an error occurs.
2
onErrorCaptured((err) => {
Registers a hook to intercept runtime errors thrown by child components.
3
errorMessage.value = err.message;
Captures and stores the error message into the reactive reference for display.
4
return false;
Prevents the error from propagating further up to parent components or crashing the app.