简体   繁体   中英

Error Handler vs. Unknown Endpoints in Express

I currently have the code below in an backend server built with express. Looking at this code, I would have expected the call to next(error) on line 11 to first hit the app.use(unknownEndpoint) middleware, resulting in a message of { error: "unknown endpoint" } to the client.

However, it does actually execute the code in the error handler. I think something in my understanding of Express if off, but I'm not sure what.

As far as I understood, all middleware are executed in order. So wouldn't that mean that unknownEndpoint would be executed every time there's an error before we could even get to the error handler?

app.get("/api/notes/:id", (request, response) => {
  Note.findById(request.params.id)
    .then((note) => {
      if (note) {
        response.json(note);
      } else {
        response.status(404).end();
      }
    })
    .catch((error) => {
      next(error);
    });
});


const unknownEndpoint = (request, response) => {
  response.status(404).send({ error: "unknown endpoint" });
};

app.use(unknownEndpoint);

const errorHandler = (error, request, response, next) => {
  console.error(error.message);

  if (error.name === "CastError") {
    return response.status(400).send({ error: "malformated id" });
  }

  next(error);
};

app.use(errorHandler);

Express is able to differentiate regular middlewares from error middlewares by checking their arity (meaning the number of arguments).

It appears as a detail of this paragraph in the documentation: https://expressjs.com/en/guide/error-handling.html#writing-error-handlers

Define error-handling middleware functions in the same way as other middleware functions, except error-handling functions have four arguments instead of three : (err, req, res, next).

So, if you call next(err) , Express looks for a middleware with 4 arguments to execute in its internal middlewares list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM