简体   繁体   中英

error handler expressjs middleware not catching errors

I'm not understanding why the error handler does not catch the error as described here :

const express = require("express");
​
const app = express();
​
app.use(function (err, req, res, next) {
  res.status(400).send("error");
});
​
app.get("*", (req, res) => {
  throw new Error("there is an error. this message will not be seen.");
});
​
app.listen(8001, () => console.log("listening 8001"));

I'm expecting to receive a payload string of "error" here but am seeing "there is an error. this message will not be seen." Thanks!

I had this problem before.

The error handler must be located on last of router set.

You should change location like this

const express = require("express");
​
const app = express();
​
app.get("*", (req, res) => {
  throw new Error("there is an error. this message will not be seen.");
});

app.use(function (err, req, res, next) {
  res.status(400).send("error");
});
​
app.listen(8001, () => console.log("listening 8001"));

express and koa read router like linear, so if error handler locate first of router set, it will not work.

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