JAVASCRIPT
Implement Global Error Handling in Vue 3
Set up a centralized global error handler in Vue 3 using `app.config.errorHandler` to catch unhandled errors from components, reactivity, and lifecycle hooks for centralized logging and reporting.
// src/main.js or src/main.ts
import { createApp } from 'vue';
import App from './App.vue';
const app = createApp(App);
// Register a global error handler
app.config.errorHandler = (err, instance, info) => {
// `err`: error instance
// `instance`: component instance where the error originated
// `info`: Vue specific error info (e.g. lifecycle hook name)
console.error('Caught a global Vue error:', err);
console.error('Originating component instance:', instance);
console.error('Vue error info:', info);
// Example: Send error to a logging service
// myLoggingService.logError({
// message: err.message,
// stack: err.stack,
// component: instance?.$.type.__name || 'Unknown',
// info: info,
// timestamp: new Date().toISOString()
// });
// You can also display a user-friendly error message
// if (process.env.NODE_ENV === 'production') {
// alert('An unexpected error occurred. Please try again.');
// }
};
app.mount('#app');
// Example component (for demonstration purposes, not part of main.js)
/*
// src/components/ErrorProneComponent.vue
<template>
<button @click="throwError">Trigger Error</button>
</template>
<script setup>
import { ref } from 'vue';
const throwError = () => {
// This error will be caught by the global error handler
throw new Error('This is a simulated component error!');
};
</script>
*/
How it works: This snippet shows how to implement a global error handler in a Vue 3 application using `app.config.errorHandler` in your `main.js` file. This handler centrally catches errors that occur within any component's lifecycle hooks, event handlers, watchers, or rendering functions. It's an invaluable tool for monitoring application health, logging errors to external services, and providing a consistent user experience during unexpected failures, without needing `try-catch` blocks everywhere.