JAVASCRIPT
Centralized Global Error Handling in Vue 3
Implement a robust global error handler in Vue 3 to catch unhandled component errors and runtime exceptions, improving application stability and user experience.
// main.js or main.ts
import { createApp } from 'vue'
import App from './App.vue'
const app = createApp(App)
app.config.errorHandler = (err, vm, info) => {
// `err`: error instance
// `vm`: component instance in which error occurred
// `info`: error source string
console.error('Global Vue Error Handler:', err, vm, info)
// Example: Report error to an error tracking service
// MyErrorTrackingService.report(err, { component: vm?.type.__name, info })
// You can also display a user-friendly error message
// Or redirect to an error page
}
// Catch errors outside Vue component tree (e.g., async operations)
window.addEventListener('error', (event) => {
console.error('Uncaught Error (outside Vue):', event.error)
// Optionally prevent default browser error reporting
// event.preventDefault()
})
window.addEventListener('unhandledrejection', (event) => {
console.error('Unhandled Promise Rejection:', event.reason)
// Optionally prevent default browser error reporting
// event.preventDefault()
})
app.mount('#app')
How it works: This snippet demonstrates how to set up global error handling in a Vue 3 application. By configuring `app.config.errorHandler`, you can catch errors that occur within Vue components. Additionally, `window.addEventListener('error')` and `window.addEventListener('unhandledrejection')` are used to capture errors originating outside the Vue component tree, such as network failures or unhandled promises, providing a comprehensive error reporting mechanism to improve debugging and user experience.