Implementing a Vue 3 Error Boundary with `onErrorCaptured`
Owner: SnippetBot
Created: 2026-11-07 00:00:29
Size: 1.63 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
// ErrorBoundary.vue
import { ref, onErrorCaptured, h } from 'vue';
export default {
name: 'ErrorBoundary',
setup(_, { slots }) {
const error = ref(null);
onErrorCaptured((err, instance, info) => {
console.error("Caught an error!", err, info, instance);
error.value = err;
// Return false to stop the error from propagating further up the tree
// or true to allow propagation to other error boundaries.
return true;
});
return () => {
if (error.value) {
return h('div', { style: 'color: red; border: 1px solid red; padding: 10px;' }, [
h('h3', 'Something went wrong!'),
h('p', error.value.message),
h('button', { onClick: () => error.value = null }, 'Reset Error'),
]);
}
return slots.default ? slots.default() : h('span', 'No content provided for ErrorBoundary');
};
},
};
// Usage in Parent Component
/*
<template>
<ErrorBoundary>
<MyComponentThatMightFail />
</ErrorBoundary>
</template>
<script setup>
import ErrorBoundary from './ErrorBoundary.vue';
// Define MyComponentThatMightFail.vue to test it:
// <template>
// <button @click="throwError">Click to throw error</button>
// <p v-if="shouldFail">{{ data.nonExistentProperty.value }}</p>
// </template>
// <script setup>
// import { ref } from 'vue';
// const shouldFail = ref(false);
// const throwError = () => {
// throw new Error("This is a simulated component error!");
// // Or cause a runtime error by accessing undefined property
// // shouldFail.value = true;
// };
// </script>
//
import MyComponentThatMightFail from './MyComponentThatMightFail.vue';
</script>
*/