Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Impara Error Handling Middleware | Error Handling and Best Practices
Express.js Essentials for Backend Development

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.

question mark

Which of the following best describes the correct signature for an error-handling middleware function in Express.js?

Seleziona la risposta corretta

Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 6. Capitolo 1

Chieda ad AI

expand

Chieda ad AI

ChatGPT

Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione

Sezione 6. Capitolo 1
some-alt