JAVASCRIPT
Implementing Global Error Handling in Vue 3 Applications
Centralize error management in your Vue 3 app using `app.config.errorHandler` to catch component-level errors, improving debugging and user experience.
// main.js
import { createApp } from 'vue';
import App from './App.vue';
const app = createApp(App);
// Global error handler for all Vue components
app.config.errorHandler = (err, instance, info) => {
// `err` is the error itself
// `instance` is the component instance that triggered the error
// `info` is a Vue-specific error info string (e.g. "render function", "mounted hook")
console.error('Vue Global Error Caught:', err);
console.error('Component Instance:', instance);
console.error('Error Info:', info);
// Here you might:
// - Send error reports to an analytics service (e.g., Sentry, Bugsnag)
// - Display a user-friendly error message or fallback UI
// - Log to a remote server
// - Perform cleanup or state reset if necessary
alert(`An application error occurred: ${err.message}. Please try again.`);
};
// Optional: Global warning handler for Vue's runtime warnings
// app.config.warnHandler = (msg, instance, trace) => {
// console.warn('Vue Global Warning Caught:', msg);
// // You can suppress specific warnings or send them to a different logging service
// };
app.mount('#app');
// ErrorProneComponent.vue
<template>
<div>
<h2>Error Prone Component</h2>
<button @click="triggerError">Trigger Runtime Error</button>
<button @click="triggerPromiseRejection">Trigger Promise Rejection (not caught by errorHandler directly)</button>
<p>Check console for error details.</p>
</div>
</template>
<script setup>
import { ref } from 'vue';
const triggerError = () => {
// This will be caught by app.config.errorHandler because it's synchronous
// and happens within a component's lifecycle/event handler.
throw new Error('This is a simulated runtime error in component!');
};
const triggerPromiseRejection = () => {
// Unhandled promise rejections are not directly caught by Vue's errorHandler
// as they are asynchronous and handled by the browser's global unhandledrejection event.
// You would typically handle these with window.addEventListener('unhandledrejection', ...)
// or by adding .catch() to your promises.
new Promise((resolve, reject) => {
setTimeout(() => {
reject(new Error('This is an unhandled promise rejection!'));
}, 100);
});
};
</script>
How it works: This snippet demonstrates how to implement global error handling in a Vue 3 application using `app.config.errorHandler`. By assigning a function to this property in `main.js`, you can catch and process all errors that occur within your Vue components, such as those in lifecycle hooks, event handlers, or render functions. The error handler receives the error, the component instance, and additional info, allowing for centralized logging, reporting to external services, or displaying user-friendly messages, significantly improving application resilience and debugging capabilities. Note that it does not catch unhandled promise rejections directly, which require a separate `window.addEventListener('unhandledrejection', ...)` handler.