Error boundaries help catch and handle errors in parts of your Vue app so the whole app doesn't break.
0
0
Error boundaries with onErrorCaptured in Vue
Introduction
When you want to show a friendly message if a part of your app crashes.
When you want to log errors from child components for debugging.
When you want to prevent one component's error from stopping the whole page.
When you want to recover gracefully from errors in specific UI sections.
Syntax
Vue
<script setup> import { onErrorCaptured } from 'vue' onErrorCaptured((error, instance, info) => { // handle or log the error return false // to stop error propagation }) </script>
onErrorCaptured is a Vue Composition API hook to catch errors in child components.
Returning false stops the error from propagating further up.
Examples
Catches errors and logs the message, then stops propagation.
Vue
<script setup> import { onErrorCaptured } from 'vue' onErrorCaptured((error) => { console.error('Error caught:', error.message) return false }) </script>
Shows an alert with info about where the error happened.
Vue
<script setup> import { onErrorCaptured } from 'vue' onErrorCaptured((error, instance, info) => { alert(`Error in component: ${info}`) return false }) </script>
Returns true to let the error continue propagating to parent handlers.
Vue
<script setup> import { onErrorCaptured } from 'vue' onErrorCaptured(() => { // ignore error and let it propagate return true }) </script>
Sample Program
This example shows a component that throws an error immediately. The ErrorBoundary catches it and shows a red error message instead of breaking the whole app.
Vue
<template>
<ErrorBoundary>
<BuggyComponent />
</ErrorBoundary>
</template>
<script setup>
import { defineComponent, ref, onErrorCaptured } from 'vue'
const BuggyComponent = defineComponent({
setup() {
const count = ref(0)
if (count.value === 0) {
throw new Error('Oops! BuggyComponent crashed.')
}
return { count }
},
template: `<div>Count: {{ count }}</div>`
})
const ErrorBoundary = defineComponent({
setup(props, { slots }) {
const errorMessage = ref('')
onErrorCaptured((error) => {
errorMessage.value = error.message
return false
})
return () => errorMessage.value
? <div role="alert" aria-live="assertive" style="color: red; font-weight: bold;">Error: {errorMessage.value}</div>
: slots.default()
}
})
</script>OutputSuccess
Important Notes
Use onErrorCaptured inside a component to catch errors from its children.
Always provide a fallback UI to keep your app usable when errors happen.
Remember to add role="alert" and aria-live="assertive" for accessibility when showing error messages.
Summary
Error boundaries catch errors in child components to prevent app crashes.
onErrorCaptured hook lets you handle errors in Vue's Composition API.
Return false to stop error propagation and show fallback UI.