javascript / expert
Snippet
Intercepting Component Failures via onErrorCaptured Stack Hooks
The onErrorCaptured hook catches errors originating from descendant component trees. Returning false from this hook halts error propagation, preventing the error from escalating up to root error handlers or tearing down the entire component tree.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import { onErrorCaptured, ref } from 'vue';export function useComponentBoundary(logCallback) {const errorState = ref(null);onErrorCaptured((err, instance, info) => {errorState.value = {error: err,component: instance?.$options?.name || 'Anonymous',location: info};if (logCallback) logCallback(err, info);return false;});return { errorState };}
vue
Breakdown
1
onErrorCaptured((err, instance, info) => {
Registers a lifecycle hook triggered when an unhandled error bubbles up from child components.
2
return false;
Halts error propagation up the parent component tree to prevent catastrophic cascade.