Error Handling Middleware
Scorri per mostrare il menu
Centralized error handling is essential in Express.js applications to ensure that errors are managed consistently and that clients receive meaningful feedback. Express.js provides a special type of middleware called error-handling middleware, which is defined with four parameters: err, req, res, and next. This middleware catches errors thrown in route handlers or other middleware, then sends a structured response to the client.
Here is an example of an error-handling middleware that catches errors and sends a JSON response:
// Error-handling middleware function
app.use(function (err, req, res, next) {
console.error(err.stack);
res.status(500).json({ error: 'Something went wrong!' });
});
In this example, the middleware logs the error stack to the console and sends a JSON response with a generic error message and a 500 status code. This approach ensures that sensitive error details are not exposed to clients, while still providing useful feedback.
The signature of error-handling middleware in Express.js is distinct because it includes four parameters: err, req, res, and next. Express automatically recognizes such functions as error handlers. To trigger this middleware, you can throw an error inside a route handler or pass an error to the next function. For example, if a route handler encounters an issue, you can call next(new Error('Custom error message')). This will skip any remaining non-error middleware and pass control directly to the error-handling middleware, allowing you to manage errors in a single, centralized location.
Grazie per i tuoi commenti!
Chieda ad AI
Chieda ad AI
Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione