Logo

Developer learning path

Node.js

Handling Errors in Express.js in Node.js

Handling Errors in Express.js

91

#description

Node.js is a popular server-side development framework used to build scalable and robust web applications. Express.js is a leading web framework built on top of Node.js, which provides various features to build web applications, such as routing, middleware, and more.

One crucial aspect of building any application is to handle errors gracefully. In Express.js, there are various ways to handle errors efficiently.

Let's discuss them one by one:

  1. Error Handling Middleware: Express.js provides a way to handle errors using middleware. Whenever an error occurs in an application, the middleware can catch that error and forward it to the next error handling middleware.

For example, consider the following middleware:

                    
function errorHandler(err, req, res, next) {
  console.log(err.stack);
  res.status(500).send('Internal Server Error');
}
                  

In the above code, whenever an error occurs, the errorHandler() middleware logs the error stack trace and sends an internal server error message to the client.

  1. Built-in Error Handling Middleware: Express.js has built-in error-handling middleware. Whenever an error occurs in the application, middleware can catch and handle the error.

For example, consider the following middleware:

                    
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).send('Internal Server Error');
});
                  

The above middleware will catch any error that occurs in the application and log the error stack trace and send an internal server error message to the client.

  1. Custom Error Handling: It is also possible to create custom error handling middleware to handle specific errors. Express.js provides a next() function that takes an error as an argument, which can be handled by custom error handling middleware.

For example, consider the following middleware:

                    
function customErrorHandler(err, req, res, next) {
  if (err.message === 'invalid input') {
    res.status(400).send('Bad Request');
  } else {
    next(err);
  }
}
                  

The above middleware checks if the error message is "invalid input" and sends a bad request response. Otherwise, it passes the error to the next error handling middleware.

In conclusion, error handling is crucial when building an application in Node.js and Express.js. With built-in middleware and the ability to create custom error handling middleware, Express.js provides many options for efficient error handling.

March 25, 2023

If you don't quite understand a paragraph in the lecture, just click on it and you can ask questions about it.

If you don't understand the whole question, click on the buttons below to get a new version of the explanation, practical examples, or to critique the question itself.