Vue3 app.config.errorHandler Property
app.config.errorHandlerIt is a very practical property that allows developers to globally capture and handle errors in applications.
1. What is app.config.errorHandler?
app.config.errorHandleris a global configuration option in Vue3, used to capture and handle uncaught errors in applications. Whether it's errors thrown in component lifecycle hooks, event handlers, or asynchronous operations, they can all beapp.config.errorHandlercaptured and handled.
2. How to use app.config.errorHandler?
To use itapp.config.errorHandlerfirst, you need to create a Vue instance and set theerrorHandlerproperty. Here is a simple example:
Example
import App from './App.vue'
const app = createApp(App)
app.config.errorHandler = (err, vm, info) => {
console.error('Caught a global error:', err)
console.error('The component instance where the error occurred:', vm)
console.error('Error message:', info)
}
app.mount('#app')
In this example, we created a Vue application and seterrorHandlerWhen an uncaught error occurs in the application,errorHandlerthe function will be called, and the error message, the component instance where the error occurred, and the error message will be passed to the function.
Parameter description:
- err: The error object, which contains detailed information about the error.
- vm: The component instance where the error occurred.
- info: A string representing the source of the error, such as
Lifecycle hooks、Event handleretc.
3. Practical application scenarios
app.config.errorHandlerThere are many application scenarios in actual development. The following are some common usages:
3.1 Error log recording
In production environments, capturing and recording error logs is very important. Throughapp.config.errorHandler, we can send the error information to the server for storage and analysis.
Example
// Send the error information to the server
fetch('/log-error', {
method: 'POST',
body: JSON.stringify({ err, vm, info })
})
console.error('Caught a global error:', err)
}
3.2 User-friendly prompts
When an error occurs in the application, we can useapp.config.errorHandlerto display user-friendly prompt messages instead of letting users see complex error stacks.
Example
alert('Sorry, the application has encountered a problem. Please try again later.')
console.error('Caught a global error:', err)
}
3.3 Error recovery
In some cases, we can try toapp.config.errorHandlerrecover from the error in it to prevent the application from crashing.
Example
console.error('Caught a global error:', err)
// Try to restore application state
vm.$forceUpdate()
}
4. Notes
- Error propagation:
app.config.errorHandlerdoes not prevent error propagation. If an error is not caught, it will still be caught by the browser and displayed in the console. - Asynchronous errors:
app.config.errorHandlercan capture errors in asynchronous operations, but you need to be aware of the error handling mechanisms of asynchronous code.
Other extensions