0
0
Vueframework~15 mins

Error boundaries with onErrorCaptured in Vue - Deep Dive

Choose your learning style9 modes available
Overview - Error boundaries with onErrorCaptured
What is it?
Error boundaries in Vue are special components that catch errors from their child components during rendering, lifecycle hooks, or event handlers. The onErrorCaptured hook is a built-in Vue Composition API function that lets you define such error boundaries easily. It helps prevent the whole app from crashing by catching errors locally and handling them gracefully. This makes your app more stable and user-friendly.
Why it matters
Without error boundaries, a single error in a component can break the entire Vue app, leaving users with a blank or broken screen. onErrorCaptured allows developers to catch these errors early and show fallback UI or log the problem without crashing the whole app. This improves user experience and helps developers find and fix bugs faster.
Where it fits
Before learning error boundaries, you should understand Vue components, the Composition API, and basic error handling in JavaScript. After mastering onErrorCaptured, you can explore advanced error reporting, global error handlers, and server-side error handling in Vue apps.
Mental Model
Core Idea
onErrorCaptured acts like a safety net around child components to catch and handle errors before they break the whole app.
Think of it like...
Imagine a safety net under a tightrope walker. If the walker slips (an error happens), the net catches them so they don’t fall to the ground (app crash). The net lets the show go on safely.
Parent Component
┌─────────────────────────┐
│ onErrorCaptured Hook     │
│  ┌───────────────────┐  │
│  │ Child Component   │  │
│  │ (may throw error) │  │
│  └───────────────────┘  │
└─────────────────────────┘
If error occurs in Child Component → onErrorCaptured catches it → Parent handles error → App continues running
Build-Up - 6 Steps
1
FoundationUnderstanding Vue component errors
🤔
Concept: Errors can happen inside Vue components during rendering or lifecycle events.
In Vue, components are like building blocks. Sometimes, code inside them can cause errors, like trying to access a missing property or calling a function that doesn’t exist. These errors normally stop the app from working properly.
Result
If an error happens inside a component, the app may crash or show a blank screen.
Knowing that errors inside components can break the whole app helps you see why catching them early is important.
2
FoundationBasics of the onErrorCaptured hook
🤔
Concept: onErrorCaptured is a Vue Composition API hook to catch errors from child components.
You can add onErrorCaptured inside a parent component’s setup function. It receives the error, the component instance where it happened, and info about the error. Returning true stops the error from propagating further.
Result
Errors thrown in child components are caught by onErrorCaptured, preventing app crash.
Understanding that onErrorCaptured catches errors from children lets you build safer components.
3
IntermediateUsing onErrorCaptured to show fallback UI
🤔Before reading on: Do you think onErrorCaptured can replace the broken component with a message? Commit to yes or no.
Concept: You can use onErrorCaptured to display a fallback UI when an error occurs.
Inside onErrorCaptured, set a reactive flag like hasError to true. In the template, check this flag to show an error message instead of the broken child component. This way, users see a friendly message instead of a crash.
Result
When a child component errors, the parent shows a fallback message and the app keeps working.
Knowing how to swap UI on error improves user experience and keeps your app stable.
4
IntermediateControlling error propagation with return value
🤔Before reading on: Does returning true from onErrorCaptured stop or allow error propagation? Commit to your answer.
Concept: Returning true from onErrorCaptured stops the error from propagating to ancestor components.
If you return true inside onErrorCaptured, Vue stops sending the error up the component tree. If you return false or nothing, the error continues to propagate and may be caught by other error boundaries or the global handler.
Result
You control whether errors bubble up or are handled locally by returning true or false.
Understanding error propagation control helps you design layered error handling strategies.
5
AdvancedStacking multiple error boundaries
🤔Before reading on: Can multiple onErrorCaptured hooks catch the same error in different components? Commit to yes or no.
Concept: Multiple nested components can each have onErrorCaptured hooks to catch errors at different levels.
If a child component throws an error, the closest parent with onErrorCaptured catches it first. If that handler returns false, the error bubbles up to the next parent’s onErrorCaptured. This lets you create layered error boundaries with different fallback UIs or logging.
Result
Errors can be caught and handled at multiple levels, allowing flexible recovery strategies.
Knowing how error boundaries stack helps build robust apps with graceful degradation.
6
ExpertIntegrating onErrorCaptured with global error handling
🤔Before reading on: Does onErrorCaptured replace Vue’s global error handler? Commit to yes or no.
Concept: onErrorCaptured works alongside Vue’s global error handler to provide both local and global error management.
Vue has a global error handler (config.errorHandler) that catches uncaught errors. onErrorCaptured catches errors locally first. If onErrorCaptured returns false or is absent, the global handler runs. You can combine both to log errors locally and report them globally.
Result
You get fine-grained local error handling plus centralized global error reporting.
Understanding the interaction between local and global error handlers enables comprehensive error management.
Under the Hood
When a child component throws an error during rendering or lifecycle, Vue’s internal error handling system triggers. It walks up the component tree looking for onErrorCaptured hooks. Each hook is called with the error details. If a hook returns true, Vue stops propagating the error further. Otherwise, it continues up until it reaches the global error handler or the root. This mechanism prevents the entire app from crashing by isolating errors to specific component branches.
Why designed this way?
Vue’s error boundary system was designed to give developers control over error handling at different levels. Instead of a single global handler, local boundaries allow graceful recovery and better user experience. The return value controlling propagation offers flexibility to decide if errors should bubble up or be contained. This design balances safety, flexibility, and simplicity.
Component Tree
┌───────────────┐
│ Root Component│
│  onErrorCaptured? ──┐
└───────┬───────┬─────┘  │
        │       │        │
┌───────▼────┐  │        │
│ Parent Comp│  │        │
│ onErrorCaptured? ──────┐
└───────┬────┘           │
        │                │
┌───────▼────┐           │
│ Child Comp │ (throws error)
└────────────┘

Error thrown → onErrorCaptured in Parent called → returns true? → stop propagation
If false → propagate to Root → global error handler
Myth Busters - 4 Common Misconceptions
Quick: Does onErrorCaptured catch errors thrown asynchronously inside setTimeout? Commit to yes or no.
Common Belief:onErrorCaptured catches all errors inside child components, including asynchronous ones.
Tap to reveal reality
Reality:onErrorCaptured only catches errors during rendering, lifecycle hooks, and event handlers, but not errors inside asynchronous callbacks like setTimeout or Promises.
Why it matters:Assuming onErrorCaptured catches async errors can lead to uncaught exceptions crashing the app unexpectedly.
Quick: If onErrorCaptured returns false, does the error stop propagating? Commit to yes or no.
Common Belief:Returning false or nothing from onErrorCaptured stops error propagation.
Tap to reveal reality
Reality:Only returning true stops propagation; returning false or nothing lets the error bubble up to ancestor handlers or the global handler.
Why it matters:Misunderstanding this causes errors to propagate unexpectedly, making debugging harder.
Quick: Can onErrorCaptured catch errors thrown inside the same component where it is declared? Commit to yes or no.
Common Belief:onErrorCaptured catches errors thrown anywhere inside the component it is declared in.
Tap to reveal reality
Reality:onErrorCaptured only catches errors from child components, not from the component itself.
Why it matters:Expecting it to catch own errors leads to missed error handling and app crashes.
Quick: Does onErrorCaptured replace the need for global error handling? Commit to yes or no.
Common Belief:Using onErrorCaptured means you don’t need Vue’s global error handler anymore.
Tap to reveal reality
Reality:onErrorCaptured complements but does not replace the global error handler; both are needed for full coverage.
Why it matters:Ignoring global error handling can miss errors outside component trees or unhandled rejections.
Expert Zone
1
onErrorCaptured hooks run synchronously during the error event, so asynchronous error handling inside them requires care.
2
Returning true from onErrorCaptured prevents ancestor error boundaries and the global handler from seeing the error, which can hide critical issues if misused.
3
Error boundaries can affect component lifecycle and state, so fallback UI should be designed to avoid infinite loops or repeated errors.
When NOT to use
Do not rely solely on onErrorCaptured for catching errors in asynchronous code like API calls or timers; use try-catch or global handlers instead. For server-side rendering, use server-specific error handling. For very simple apps, global error handling might suffice without local boundaries.
Production Patterns
In production Vue apps, developers use onErrorCaptured to show user-friendly fallback UIs and log errors locally. They combine it with global error handlers to send error reports to monitoring services. Layered error boundaries allow isolating errors to specific UI parts, improving app resilience and debugging.
Connections
Try-Catch in JavaScript
onErrorCaptured is like a component-level try-catch block for Vue components.
Understanding try-catch helps grasp how onErrorCaptured catches errors locally and controls propagation.
Exception Handling in Object-Oriented Programming
Both provide structured ways to catch and handle errors to prevent program crashes.
Knowing OOP exception handling clarifies the layered error boundary concept in Vue.
Safety Nets in Circus Performances
Both catch failures early to prevent catastrophic outcomes.
Recognizing error boundaries as safety nets helps appreciate their role in user experience and app stability.
Common Pitfalls
#1Expecting onErrorCaptured to catch errors thrown asynchronously inside setTimeout.
Wrong approach:setup() { onErrorCaptured((err) => { console.log('Caught error:', err) return true }) setTimeout(() => { throw new Error('Async error') }, 1000) }
Correct approach:setup() { onErrorCaptured((err) => { console.log('Caught error:', err) return true }) setTimeout(() => { try { throw new Error('Async error') } catch (e) { console.error('Caught async error:', e) } }, 1000) }
Root cause:onErrorCaptured only catches synchronous errors during rendering or lifecycle, not asynchronous errors.
#2Returning false or nothing from onErrorCaptured expecting to stop error propagation.
Wrong approach:onErrorCaptured((err) => { console.log('Error:', err) // no return or return false })
Correct approach:onErrorCaptured((err) => { console.log('Error:', err) return true // stops propagation })
Root cause:Only returning true stops error propagation; false or no return lets errors bubble up.
#3Declaring onErrorCaptured in a component expecting it to catch errors thrown inside itself.
Wrong approach:setup() { onErrorCaptured((err) => { console.log('Caught error:', err) return true }) throw new Error('Error inside same component') }
Correct approach:setup() { try { throw new Error('Error inside same component') } catch (err) { console.log('Caught error:', err) } onErrorCaptured((err) => { console.log('Caught child error:', err) return true }) }
Root cause:onErrorCaptured only catches errors from child components, not the component itself.
Key Takeaways
onErrorCaptured is a Vue Composition API hook that catches errors from child components to prevent app crashes.
Returning true from onErrorCaptured stops error propagation, letting you control error handling layers.
onErrorCaptured only catches synchronous errors during rendering, lifecycle, or event handlers, not asynchronous errors.
Combining local error boundaries with global error handlers provides comprehensive error management in Vue apps.
Designing fallback UI inside error boundaries improves user experience by showing friendly messages instead of broken screens.