簡體   English   中英

錯誤處理程序 expressjs 中間件未捕獲錯誤

[英]error handler expressjs middleware not catching errors

我不明白為什么錯誤處理程序沒有捕獲此處描述的錯誤:

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"));

我希望在這里收到一個“錯誤”的有效負載字符串,但我看到“有一個錯誤。這條消息將不會被看到。” 謝謝!

我以前遇到過這個問題。

錯誤處理程序必須位於路由器集的最后一個。

你應該像這樣改變位置

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 和 koa 像線性一樣讀取路由器,所以如果錯誤處理程序定位到路由器集合的第一個,它將不起作用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM