JAVASCRIPT
Implementing a Global Error Handler
Set up a global error handler in Vue 3 to catch unhandled errors from components, lifecycle hooks, and event handlers, improving application stability and debugging.
// main.js
import { createApp, isVNode } from 'vue';
import App from './App.vue';
const app = createApp(App);
app.config.errorHandler = (err, vm, info) => {
// `err` is the error object
// `vm` is the component instance where the error occurred
// `info` is a Vue-specific error info string (e.g. "render function")
console.error("Global error caught!");
console.error("Error:", err);
console.error("Component:", vm);
console.error("Info:", info);
// Log to an error tracking service (e.g., Sentry, Bugsnag)
// Sentry.captureException(err, { extra: { component: vm, info: info } });
// Optionally, display a user-friendly error message
// if (!isVNode(vm)) { // Check if vm is a component instance
// // Maybe update a global error state to show a banner
// }
};
app.mount('#app');
// Example component that throws an error (e.g., ErrorComponent.vue)
<template>
<div>
<button @click="throwError">Click to throw error</button>
</div>
</template>
<script setup>
const throwError = () => {
// Simulate an error
throw new Error("Something went wrong in ErrorComponent!");
};
</script>
How it works: This snippet demonstrates how to set up a global error handler in a Vue 3 application using `app.config.errorHandler`. This handler catches unhandled errors that occur during component rendering, lifecycle hooks, watch functions, and event handlers throughout your application. It provides access to the error object, the component instance where the error originated, and additional Vue-specific information, allowing you to centralize error logging, send errors to external tracking services, or display graceful fallback UIs to users.