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

Error Handling Middleware

Sveip for å vise menyen

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?

Velg det helt riktige svaret

Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 6. Kapittel 1

Spør AI

expand

Spør AI

ChatGPT

Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår

Seksjon 6. Kapittel 1
some-alt