How to do error handling in a REST API with Express middleware routing

10,170

A little late to the game but, this is how i handle errors in my express based API projects.

There are mainly 2 reasons error can happen.

  1. User try to access a route which is not defined.

  2. Something can go wrong when user is interacting with database. Which will directly throw an error.

For the first type of error, this is how i manage it.

app.use((req, res, next) => {
  const error = new Error('Not Found!');
  error.status = 404;
  next(error);
});
  • When you declare this middle ware after you have defined all the routes, and when user try to request an invalid route it will go through this middle ware.

  • I am creating a new error object using the default Error object in NodeJs. Then i am assigning a status and passing it to a next main error handler.

Second type of errors. which can be caused by database related errors or validation errors etc.

This is how i handle those.

app.use((error, req, res, next) => {
  res.status(error.status || 500);
  res.json({
    error: {
      message: error.message,
    },
  });
});
  • If the error is the not found error which is coming from the previous handler, then make an object and send the error details.

  • In database interaction if something goes wrong it directly throws an error, then this middle ware will catch it and assign it a status and take the message from thrown error and make it into an object and return it as json.

This is the most convenient way i found to handle errors.

I learned this from here.

Share:
10,170
user007
Author by

user007

Updated on June 04, 2022

Comments

  • user007
    user007 almost 2 years

    Assume we have a REST API with the following route:

    app.post("/accounts/:accountId", isAuthorized, isSelf, updateAccount);

    Within this scenario, a lot can go wrong. The user could be unauthorized because he is not logged in, or because he is trying to update an account which is not his, or he is missing a required property value. Using middleware you can extract certain validation, so it can be used across multiple routes.

    The situation

    I am creating a POST to this route, but I do not sent an authorization header. The isAuthorized, successfully captures the error, and instead of calling the next function, it will use a res.send(403) or something. The isSelf and updateAccount function would do something similair.

    The problem

    I need to manually follow a pattern across all the functions to return a similar error handling. Which is - as a developer - pretty error prone. Since it's fairly easy to mess up conventions when you would need to manage it across all kind of files.

    The question

    What is the simplest way to manage errors?

    Please note that all the middleware functions are custom functions, so they can be written to follow a generalized approach.