javascript / intermediate
Snippet
Capturing Errors with onErrorCaptured
The onErrorCaptured lifecycle hook acts like a local error boundary. It catches errors coming from any descendant component, allowing you to display fallback UI or log errors without crashing the entire application.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<script setup>import { onErrorCaptured, ref } from 'vue';const error = ref(null);onErrorCaptured((err, instance, info) => {error.value = err.message;console.error('Captured in component:', info);return false; // Prevents the error from propagating further});</script><template><div v-if="error" class="error-banner">Something went wrong: {{ error }}</div><ChildComponent v-else /></template>
vue
Breakdown
1
onErrorCaptured((err, instance, info) => { ... })
Hook that receives the error, the component instance, and an info string about where it happened.
2
return false;
Returning false stops the error from bubbling up to the global error handler.