Handling errors in Node.js effectively is crucial for building robust applications. In Express.js, one of the most popular Node.js web application frameworks, you can handle errors using middleware. Here's a step-by-step guide on how to set up error handling so that errors are delegated to an error-handling middleware:
1. Basic Error Middleware
First, understand what an error-handling middleware is in Express. It's a function that has four parameters: err, req, res, and next.
function errorHandler(err, req, res, next) {
// Log the error, for development
console.error(err.stack);
// Respond to client
res.status(500).json({ message: err.message });
}
2. Using next to Pass Errors
In your route handlers or other middleware, use the next function to pass errors to the error-handling middleware:
app.get('/some-route', (req, res, next) => {
// Simulate an error
const error = new Error('Something went wrong!');
error.status = 500; // Optional: set status code
next(error); // Pass the error to the error-handling middleware
});
3. Asynchronous Code
For asynchronous operations, like those involving promises or async/await, make sure to pass errors to next:
app.get('/async-route', async (req, res, next) => {
try {
const result = await someAsyncOperation();
res.json(result);
} catch (err) {
next(err); // Pass the error to the error-handling middleware
}
});
4. Central Error-Handling Middleware
Place the error-handling middleware after all other routes and middleware:
// Other middlewares and routes
// ...
// Error-handling middleware (should be defined last)
app.use(errorHandler);
5. Customizing Error Responses
You can customize error responses based on different criteria:
function errorHandler(err, req, res, next) {
const statusCode = err.status || 500; // Use the specific status code or default to 500
// In production, avoid leaking stack traces to the clients
const response = {
message: err.message,
};
// Optionally include error details in development
if (process.env.NODE_ENV === 'development') {
response.stack = err.stack;
}
res.status(statusCode).json(response);
}
6. Using Libraries
You can also use middleware libraries for more comprehensive error handling, such as:
http-errors: For creating HTTP errors in a consistent manner.
express-async-errors: A small middleware to handle errors in async routes without try-catch blocks.
npm install http-errors express-async-errors
Include them at the top of your server file:
require('express-async-errors'); // Supports async error handling
const createError = require('http-errors');
// Example of using http-errors for an endpoint
app.get('/some-route', (req, res, next) => {
next(createError(404, 'This is a not found error'));
});
Summary
By structuring your Node.js application with centralized error handling, you ensure that unexpected issues are managed gracefully and consistently, which leads to more maintainable code and better user experiences.