简体   繁体   English

错误处理程序 expressjs 中间件未捕获错误

[英]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. express 和 koa 像线性一样读取路由器,所以如果错误处理程序定位到路由器集合的第一个,它将不起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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