Handling uncaught exceptions and unhandled promise rejections within an Express.js application will be essential in developing highly robust and resilient systems. Here's how you should handle these situations:
Handling Uncaught Exceptions
Uncaught exceptions occur if an error is not caught within the application's code. This can crash the Node.js process if unhandled.
Example:
process.on('uncaughtException', (err) => {
console.error('Uncaught Exception:', err.message);
console.error(err.stack);
// Optionally, you can do cleanup here
process.exit(1); // Exit the process after logging the error
});
When to Use: Use this handler to log critical errors and shut down the server gracefully. Do not use it for normal error handling.
Handle Unhandled Promise Rejections
Unhandled promise rejections happen when a Promise is rejected and no.catch() or try.catch is used to handle the rejection.
Example:
process.on('unhandledRejection', (reason, promise) => {
console.error('Unhandled Rejection at:', promise, 'reason:', reason);
// Optionally, you can perform cleanup tasks here
});
Using Middleware to Handle Errors
Express.js has an inbuilt system for centralizing error handling using middleware.
Example
// Set up an error-handling middleware
app.use((err, req, res, next) => {
console.error('Error:', err.message);
res.status(err.status || 500).json({
error: {
message: err.message,
}
});
});
Best Practice: Place this middleware after all other routes to catch errors that occur in route handlers.