javascript / expert
Snippet
Component Boundary Exception Interception via onErrorCaptured Lifecycle Hook
The `onErrorCaptured` hook captures errors originating from child component trees. Returning `false` prevents the error from bubbling further up the component hierarchy, effectively turning the parent component into an isolated error boundary.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import { ref, onErrorCaptured } from 'vue';export function useComponentBoundaryHandler(fallbackLogger) {const errorState = ref(null);onErrorCaptured((err, targetInstance, info) => {errorState.value = {message: err instanceof Error ? err.message : String(err),componentName: targetInstance?.$options.name || 'Anonymous',lifecyclePhase: info};fallbackLogger(err, info);return false;});return { errorState, clearError: () => { errorState.value = null; } };}
vue
Breakdown
1
onErrorCaptured((err, targetInstance, info) => {
Registers a handler invoked when descendant components throw uncaught runtime exceptions.
2
componentName: targetInstance?.$options.name || 'Anonymous',
Inspects the instance options of the originating component to extract metadata.
3
return false;
Halts error propagation to upper ancestor component error boundaries or app level.