LearnAI ToolsCareerPractice BuildsPlayContact
Lesson 3714 min read

Error Handling

Catch and handle errors gracefully in Vue components using onErrorCaptured and the global error handler.

Errors in Async Code

Most everyday error handling in Vue is plain JavaScript try/catch around an async operation — as already shown in the data-fetching lesson — rather than a special Vue API.

onErrorCaptured

onErrorCaptured lets a component catch errors thrown by any of its descendants during rendering, an event handler, or a lifecycle hook — similar in spirit to a React error boundary.

<script setup>
import { ref, onErrorCaptured } from 'vue';
const error = ref(null);
onErrorCaptured((err) => {
error.value = err;
return false; // stop the error from propagating further up
});
</script>
<template>
<p v-if="error">Something went wrong: {{ error.message }}</p>
<slot v-else />
</template>

Global Error Handler

For a last-resort, app-wide catch-all — logging every uncaught error to a monitoring service, for example — register a handler on the app instance.

// main.js
app.config.errorHandler = (err, instance, info) => {
console.error('Global error:', err, info);
// send to an error tracking service
};

A Simple Error Boundary Component

Wrapping onErrorCaptured in a reusable component gives you a drop-in error boundary for any risky subtree.

<!-- ErrorBoundary.vue -->
<script setup>
import { ref, onErrorCaptured } from 'vue';
const hasError = ref(false);
onErrorCaptured(() => {
hasError.value = true;
return false;
});
</script>
<template>
<p v-if="hasError">Something went wrong in this section.</p>
<slot v-else />
</template>
<template>
<ErrorBoundary>
<RiskyWidget />
</ErrorBoundary>
</template>

FAQs

Yes — it catches errors thrown during rendering, watchers, and lifecycle hooks, as well as most synchronous errors in event handlers within its descendants.

It stops the error from continuing to propagate up to any parent's own onErrorCaptured or the global handler — omit it (or return true/undefined) to let the error keep bubbling.

Summary

onErrorCaptured gives you component-level error boundaries, and app.config.errorHandler catches anything that slips past every boundary. Next, you'll learn KeepAlive and Suspense for managing component caching and async loading states.

Next Lesson →

KeepAlive & Suspense