Error handling in Vue

Intermediate · 29 min

What Vue catches for you, app.config.errorHandler for reporting, onErrorCaptured for error-boundary components, and the async errors that still slip past both.

Before thisAsync components and SuspensePlugins

DejaVue · 29 min

Error handling in Vue

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by DejaVueReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • Vue wraps the code it calls for you — renders, `setup`, lifecycle hooks, watchers, template event handlers, custom directive hooks and transition hooks — and routes errors thrown there into its own error-handling chain; promises returned from hooks and handlers are covered too.
  • Unhandled errors are re-thrown in development but only logged to the console in production, so without a handler a production error reaches no one; `app.config.throwUnhandledErrorInProduction` (Vue 3.5+) changes that default.
  • `app.config.errorHandler(err, instance, info)` is the single app-wide place to report errors to a tracking service; in production `info` is a short code you look up in Vue's error reference.
  • `onErrorCaptured` runs in an ancestor when a descendant throws, bottom to top like DOM event bubbling; returning `false` marks the error handled and stops both further hooks and the app-level handler.
  • An error-boundary component in Vue is just `onErrorCaptured` plus a slot and a ref, with no class component needed as in React; its error state must not re-render the content that failed, or it loops.
  • Code Vue doesn't call — a `setTimeout` callback, a promise nobody returns or awaits — never enters this chain; it needs its own `try`/`catch`, or a `window` `unhandledrejection`/`error` listener as a last resort.

The error you never hear about

Users do things you didn’t test. An API returns null where you expected an array, a third-party widget throws on an odd input, a translation key is missing. The question isn’t whether errors happen in production, it’s whether anyone finds out.

Vue’s default answer is split by environment. In development, an unhandled error is re-thrown, which makes it loud — you see it in the overlay and console immediately. In production, Vue only logs it to the console and carries on, to keep a single broken widget from crashing the page. That’s kind to users and useless to you: the console it logged to is on someone else’s laptop.

Everything in this lesson is about intercepting errors before that happens — at the app level to report them, and at the component level to show something better than a broken section. General JavaScript error mechanics, such as try/catch and custom error classes, are in error handling and custom errors.

What Vue catches for you

Vue can only catch errors in code it calls. That covers most of a component’s life:

  • render functions and templates
  • setup(), including <script setup>
  • lifecycle hooks like onMounted
  • watcher callbacks
  • event handlers bound in the template with @click and friends
  • custom directive hooks
  • <Transition> JavaScript hooks

When one of those returns a promise — an async onMounted, an async click handler — Vue also attaches a rejection handler, so an awaited fetch failing inside it is caught too.

What Vue doesn’t call, it can’t catch:

onMounted(() => {
  // caught: Vue called this function
  // throw new Error('a')

  setTimeout(() => {
    // NOT caught: the browser calls this later, not Vue
    throw new Error('b')
  }, 1000)

  // NOT caught: the promise is created but never returned or awaited
  fetch('/api/x').then((r) => r.json()).then((d) => d.missing.field)
})

Fire-and-forget promises and timer callbacks need their own try/catch or .catch(). As a last-resort net, window.addEventListener('unhandledrejection', ...) and window.addEventListener('error', ...) see what escapes everything else.

app.config.errorHandler: one place to report

The app instance has a single global hook for every error that propagates out of a component:

// main.js
import { createApp } from 'vue'
import App from './App.vue'

const app = createApp(App)

app.config.errorHandler = (err, instance, info) => {
  // err: the thrown value
  // instance: the component it came from (or null)
  // info: where it happened, e.g. a lifecycle hook or event handler
  reportToTracker(err, { component: instance?.$options.name, info })
}

app.mount('#app')

In development info is a readable string. In production builds it’s shortened to a code, mapped to text in the docs’ production error reference, to keep the bundle small.

Defining an errorHandler replaces the default behavior, so the error is no longer logged or re-thrown unless you do it yourself. This is usually wrapped in a plugin — error-tracking SDKs such as Sentry’s Vue integration install themselves exactly this way, which is why plugins are a prerequisite here.

Vue 3.5 added app.config.throwUnhandledErrorInProduction = true for teams who would rather production behave like development and throw, so that a global monitor listening on window sees unhandled errors.

onErrorCaptured: catching errors from below

The global handler is for reporting. To change what the user sees, you need a component that reacts when something inside it fails. onErrorCaptured registers a hook that runs when an error propagates up from any descendant:

<script setup>
import { onErrorCaptured } from 'vue'

onErrorCaptured((err, instance, info) => {
  console.warn('child failed in', info)
  // return nothing: the error keeps propagating
  // return false: handled, stop here
})
</script>

The propagation rules mirror DOM event bubbling:

  • When a component throws, every onErrorCaptured up the parent chain runs, nearest ancestor first.
  • After the hooks, the error still reaches app.config.errorHandler, so reporting stays centralized.
  • If a hook returns false, propagation stops: no further hooks, and no app-level handler.
  • If a hook itself throws, both its error and the original go to app.config.errorHandler.

The hook only sees errors from children, not from the component that registers it. A component can’t catch its own render error; its parent has to.

Building an error boundary

Combine onErrorCaptured with a slot and you have a reusable boundary:

<!-- ErrorBoundary.vue -->
<script setup>
import { ref, onErrorCaptured } from 'vue'

const error = ref(null)

onErrorCaptured((err) => {
  error.value = err
  return false // handled here; remove if you also want global reporting
})

function reset() {
  error.value = null
}
</script>

<template>
  <slot v-if="!error" />
  <slot v-else name="fallback" :error="error" :reset="reset">
    <p>Something went wrong.</p>
    <button @click="reset">Try again</button>
  </slot>
</template>
<ErrorBoundary>
  <RevenueChart :data="stats" />
  <template #fallback="{ reset }">
    <p>The chart couldn't load.</p>
    <button @click="reset">Retry</button>
  </template>
</ErrorBoundary>

The v-if/v-else matters. The docs warn that the error state must not render the content that caused the error: if the boundary kept rendering the failing child next to a banner, the child would throw again, the hook would fire again, and the page would loop. Clicking “Retry” clears the error, which re-mounts the child for another attempt. In practice you’d often keep return false out and let the error reach the global handler too, so it still gets reported.

Compare React’s error boundaries, which still need a class component with getDerivedStateFromError and componentDidCatch. Vue’s version is an ordinary composition hook, and it catches errors from event handlers and async hooks as well, which React’s boundaries don’t. Nuxt ships a ready-made <NuxtErrorBoundary> built on the same idea.

This boundary is also the error half of <Suspense>: put the <Suspense> inside it and a failing async setup or async component lands in the fallback (async components and Suspense). For a single lazy-loaded component, defineAsyncComponent’s errorComponent option is a more local alternative.

Expected errors aren’t exceptions

Much of what users experience as “errors” — a 404 from the API, a validation failure, an expired session — isn’t a bug, and shouldn’t be thrown into the error chain at all. Handle those where they happen, as normal state:

<script setup>
import { ref } from 'vue'
const status = ref('idle')
const message = ref('')

async function save(form) {
  status.value = 'saving'
  const res = await fetch('/api/profile', { method: 'POST', body: JSON.stringify(form) })
  if (!res.ok) {
    status.value = 'error'
    message.value = res.status === 409 ? 'That username is taken.' : 'Could not save. Try again.'
    return
  }
  status.value = 'saved'
}
</script>

Keep onErrorCaptured and the global handler for the unexpected. That’s also where good messages matter most: say what failed and what the user can do next, not “An error occurred.”

What the video covers

In this episode of the DejaVue podcast, Alexander Lichter and Michael Thiessen work through the whole range: the error page, writing useful error messages, Vue’s global error handler (3:11), the Vue 3.5 option for throwing unhandled errors in production (11:10), component-level handling (13:07), <NuxtErrorBoundary>, defineAsyncComponent, request-based handling and error tracking. It’s a conversation rather than a coding session, and roughly a third is Nuxt-specific (the vue:error hook, useFetch defaults), so the code above is the prose’s job. Michael’s Vue.js Nation talk below goes deeper on the Nuxt side for readers heading to Nuxt fundamentals.

Where this fits

That completes the built-in components. The next group starts on routing with Vue Router fundamentals, where <KeepAlive>, <Transition> and <Suspense> meet <RouterView>. Inspecting errors and component state while debugging is covered in debugging with Vue Devtools.

Check yourself

  1. 01Your app has no error handler configured. A component throws during render in production. What does the user see, and what does your team learn?

    In production, Vue's default handler only logs the error to the browser console, so the app keeps running with that component broken or missing, and nobody on the team hears about it because the console is on the user's machine. In development the same error is re-thrown so it's impossible to miss. Configuring `app.config.errorHandler` to report to a tracking service, or setting `throwUnhandledErrorInProduction` on Vue 3.5+ so a global monitor sees it, is how the team finds out.

  2. 02A `ProductCard` throws inside a `ProductGrid`, which sits inside `ShopPage`. Both `ProductGrid` and `ShopPage` register `onErrorCaptured`, and an `app.config.errorHandler` is set. In what order do they run, and how do you stop the error at `ProductGrid`?

    The hooks run bottom to top: `ProductGrid`'s `onErrorCaptured` first, then `ShopPage`'s, and finally `app.config.errorHandler`. If `ProductGrid`'s hook returns `false`, the error is treated as handled, so `ShopPage`'s hook and the app-level handler are not called for it.

  3. 03An `onMounted(() => { setTimeout(() => { throw new Error('boom') }, 0) })` error doesn't reach `onErrorCaptured` or `app.config.errorHandler`. Why?

    Vue only catches errors in code it calls itself, plus promises that code returns. The `onMounted` callback finishes immediately after scheduling the timer; the timer callback is later called by the browser, not by Vue, so its error goes straight to the global `window` error event. It needs a `try`/`catch` inside the callback, or a `window.addEventListener('error', ...)` safety net.

  4. 04A homemade `<ErrorBoundary>` sets `error.value = err` in `onErrorCaptured` and keeps rendering its default slot underneath a warning banner. The page freezes. What is wrong?

    Rendering the default slot again re-renders the child that threw, which throws again, which triggers `onErrorCaptured` again, causing an infinite render loop. The Vue docs warn that the error state must not render the original content that caused the error. The boundary should render only the fallback while `error` is set, and offer a reset that clears it to try the content again.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark