javascript / intermediate
Snippet
Capturing Component Tree Errors Gracefully with onErrorCaptured
The onErrorCaptured lifecycle hook catches errors propagating from descendant child components within the Vue render tree. By returning false from the hook handler, the error propagation is halted, preventing it from bubbling up to global error handlers or crashing the parent application context.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import { ref, onErrorCaptured } from 'vue';export default {setup() {const errorState = ref(null);onErrorCaptured((err, instance, info) => {errorState.value = { message: err.message, hookLocation: info };return false;});const resetError = () => {errorState.value = null;};return { errorState, resetError };}};
vue
Breakdown
1
onErrorCaptured((err, instance, info) => {
Registers an error boundary handler receiving the caught Error object, the throwing component instance, and lifecycle information string.
2
errorState.value = { message: err.message, hookLocation: info };
Stores error details in a reactive state reference to render localized fallback UI.
3
return false;
Stops the error from bubbling further up the Vue component hierarchy.