0 day streak
javascript / intermediate
Snippet

Capturing and Classifying Unhandled Component Exceptions via onErrorCaptured

The `onErrorCaptured` lifecycle hook intercepts uncaught errors bubbling up from descendant components. By inspecting the error object with JavaScript's `instanceof Error` check and categorizing based on its message, components can build fine-grained internal error boundaries. Returning `false` prevents the error from propagating further up to global error handlers.

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 function useErrorCatcher() {
const activeError = ref(null);
const errorSeverity = ref('none');
onErrorCaptured((err, targetInstance, info) => {
const message = err instanceof Error ? err.message : String(err);
const isNetwork = message.toLowerCase().includes('network') || message.toLowerCase().includes('fetch');
activeError.value = { message, lifecycleHook: info };
errorSeverity.value = isNetwork ? 'warning' : 'critical';
return false;
});
return { activeError, errorSeverity };
}
vue
Breakdown
1
onErrorCaptured((err, targetInstance, info) => {
Registers a hook that triggers whenever any child component throws an unhandled error.
2
const message = err instanceof Error ? err.message : String(err);
Safely extracts the message whether the thrown item is a standard Error instance or primitive value.
3
return false;
Prevents the error from propagating upward to parent components or window.onerror.