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

Error Handling Middleware

メニューを表示するにはスワイプしてください

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?

正しい答えを選んでください

すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 6.  1

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

セクション 6.  1
some-alt