JAVASCRIPT
Implementing Global Error Handling in a Vue 3 Application
Catch and manage uncaught errors across your entire Vue 3 application using `app.config.errorHandler` to improve debugging, logging, and user experience.
// main.js
import { createApp } from 'vue';
import App from './App.vue';
const app = createApp(App);
// Configure global error handler
app.config.errorHandler = (err, instance, info) => {
// `err`: The error object
// `instance`: The component instance that triggered the error
// `info`: A Vue-specific error info string (e.g., 'render function')
console.error('An unhandled error occurred in Vue:', err);
console.error('Component instance:', instance);
console.error('Vue error info:', info);
// Example: Send error to an error reporting service
// MyErrorReporter.send(err, { component: instance?.$.type.__name, info: info });
// Optionally, display a user-friendly error message
// You might want to use a global state for this, e.g., Pinia or a simple reactive object
// globalErrorState.setError('An unexpected error occurred. Please try again.');
};
// You can also catch errors outside of Vue components (e.g., in async operations)
window.addEventListener('error', (event) => {
console.error('Unhandled JavaScript error:', event.error);
// Optional: prevent default browser error logging
// event.preventDefault();
});
window.addEventListener('unhandledrejection', (event) => {
console.error('Unhandled Promise rejection:', event.reason);
// Optional: prevent default browser error logging
// event.preventDefault();
});
app.mount('#app');
// App.vue
<template>
<div>
<h1>Global Error Handling Demo</h1>
<p>Click the button to trigger an error.</p>
<button @click="triggerError">Trigger Vue Error</button>
<button @click="triggerAsyncError">Trigger Async Error</button>
</div>
</template>
<script setup>
function triggerError() {
// This error will be caught by app.config.errorHandler
throw new Error('This is a simulated Vue component error!');
}
async function triggerAsyncError() {
// This promise rejection will be caught by window.unhandledrejection
// If not caught, app.config.errorHandler won't catch it directly because it's async outside render/lifecycle
await Promise.reject('This is a simulated unhandled promise rejection!');
}
</script>
How it works: This snippet demonstrates how to set up global error handling in a Vue 3 application using `app.config.errorHandler` in `main.js`. This function acts as a central catch-all for errors that occur within Vue components during rendering, reactivity, or lifecycle hooks. It receives the error object, the component instance, and Vue-specific info, allowing for centralized logging, reporting to external services, or displaying user-friendly messages. Additionally, it includes listeners for `window.onerror` and `window.onunhandledrejection` to catch uncaught synchronous JavaScript errors and unhandled promise rejections that might occur outside the Vue component tree, ensuring comprehensive error coverage for the entire application.