javascript / expert
Snippet
Functional Error Boundary Component
Leveraging Vue's functional capabilities and the onErrorCaptured hook, this pattern creates a localized error perimeter that prevents runtime exceptions from crashing the entire component tree.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import { ref, onErrorCaptured, h } from 'vue';export const ErrorBoundary = {setup(_, { slots }) {const error = ref(null);onErrorCaptured((err) => {error.value = err;return false; // Prevent error from propagating further});return () => error.value? h('div', { class: 'error-ui' }, error.value.toString()): slots.default?.();}};
vue
Breakdown
1
onErrorCaptured((err) => {
A lifecycle hook that captures errors propagating from any descendant component.
2
return false;
Returning false stops the error from bubbling up to the global error handler or parent boundaries.
3
return () => error.value ? ...
A render function that conditionally displays an error UI or the default slot content.