1. Error-Handling Middleware:
Express.js provides a built-in error-handling middleware mechanism. Define an error-handling middleware function with four arguments: (err, req, res, next).
Place this middleware function at the end of your middleware stack to catch any errors that occur in the preceding middleware or route handlers.
Here's an example:
const express = require('express');
const app = express();
// ... other middleware and routes
// Error-handling middleware
app.use((err, req, res, next) => {
console.error(err.stack); // Log the error for debugging
res.status(500).send('Something went wrong!');
});
Use the process.on('uncaughtException', handler) event to catch unhandled exceptions that occur outside of Express.js's request-response cycle.
This is a safety net, and you should ideally handle all exceptions within your route handlers or middleware.
process.on('uncaughtException', (err) => {
console.error('Uncaught Exception:', err);
// Gracefully shut down the server or perform other necessary cleanup
process.exit(1);
});
3. Handling Promise Rejections:
Use the process.on('unhandledRejection', handler) event to catch unhandled promise rejections.
Similar to uncaught exceptions, this is a safety net, and you should handle promise rejections gracefully within your code.
process.on('unhandledRejection', (reason, promise) => {
console.error('Unhandled Rejection at:', promise, 'reason:', reason);
// Gracefully shut down the server or perform other necessary cleanup
});
4. Asynchronous Error Handling with async/await:
When using async/await, use try...catch blocks to handle errors within your asynchronous route handlers.
app.get('/', async (req, res) => {
try {
const data = await someAsyncOperation();
res.send(data);
} catch (err) {
next(err); // Pass the error to the error-handling middleware
}
});