0 day streak
javascript / expert
Snippet

Component-Level Error Boundaries via onErrorCaptured

onErrorCaptured is a specialized lifecycle hook that acts like a 'try-catch' for the entire component sub-tree. It intercepts errors from child component renders, watchers, and event listeners. Returning 'false' is critical as it prevents the error from bubbling up to the global app handler, allowing for localized graceful degradation.

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 default {
setup() {
const error = ref(null);
onErrorCaptured((err, instance, info) => {
error.value = err.message;
console.error(`Error in ${instance.$options.name}:`, info);
// Return false to stop the error from propagating further up
return false;
});
return { error };
}
}
vue
Breakdown
1
onErrorCaptured((err, instance, info) => {
Hook that triggers when any descendant component throws an unhandled error.
2
return false;
Stops the error propagation, effectively 'catching' it at this level.