简体   繁体   中英

Could you explain how error handling works with Express middlewares?

I am working my way through a book titled "Get Programming with Node.js".

Here is the code I don't quite understand:

https://github.com/JonathanWexler/get-programming-with-nodejs/tree/master/unit_2/lesson_12_capstone/finish/confetti_cuisine

errorController.js

const httpStatus = require("http-status-codes");

exports.pageNotFoundError = (req, res) => {
  let errorCode = httpStatus.NOT_FOUND;
  res.status(errorCode);
  res.render("error");
};

exports.internalServerError = (error, req, res, next) => {
  let errorCode = httpStatus.INTERNAL_SERVER_ERROR;
  console.log(`ERROR occurred: ${error.stack}`);
  res.status(errorCode);
  res.send(`${errorCode} | Sorry, our application is taking a nap!`);
};

main.js

const express = require("express"),
  app = express(),
  homeController = require("./controllers/homeController"),
  errorController = require("./controllers/errorController"),
  layouts = require("express-ejs-layouts");

app.set("view engine", "ejs");
app.set("port", process.env.PORT || 3000);
app.use(
  express.urlencoded({
    extended: false
  })
);
app.use(express.json());
app.use(layouts);
app.use(express.static("public"));

app.get("/", (req, res) => {
  res.render("index");
});

app.get("/courses", homeController.showCourses);
app.get("/contact", homeController.showSignUp);
app.post("/contact", homeController.postedSignUpForm);

app.use(errorController.pageNotFoundError);
app.use(errorController.internalServerError);

app.listen(app.get("port"), () => {
  console.log(`Server running at http://localhost:${app.get("port")}`);
});

My question:

How does Express know when to run "pageNotFoundError" or "internalServerError"?

Is it the case, that if there is a request, that is handled by a corresponding route's render method, all render or send methods within middleware's or elsewhere are ignored? This is probably far from correct, but does something like this happen?

When an exception occurs, express will call the next() function behind the scenes. Next calls the subsequent middleware function.

When one of your HTTP methods returns successfully, the error middleware functions are never reached.

You can read here for more details.

Edit:

So this is a bit tricky. The pageNotFoundError does not actually occur after an exception is thrown. Rather, it is encountered after none of the get/post routes match. So if a request was made to '/nonexistent-path/*', next would be called until pageNotFoundError is hit.

However, if an actual exception is thrown, pageNotFoundError would not be called because it does not accept error as an argument in its method signature. Only internalServerError will be called, because it's the only middleware that accepts error as an argument.

in Express js as @Greg said we have next() . simply, it's like a switch case that checks routes and give request to that route but if route not founded it give you to pagenotfound route and if it's unavailable, it give you internalserverError route.

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