【发布时间】:2020-09-16 02:43:03
【问题描述】:
我正在尝试为我的 Express 路由使用自定义错误处理程序,但无法使其正常工作。我关注了documentation,他们说您必须将您的处理程序放在use 链的最末端,但它看起来仍然像调用了默认错误处理程序。
我已经将我的项目简化为非常基本的,这就是我所拥有的。我只是在App 实例上调用start 方法来让服务器开始监听。
import * as express from "express";
import { Express, Request, Response } from "express";
import * as bodyParser from "body-parser";
export class App {
private static readonly port: number = 8080;
private app: Express;
public constructor() {
this.app = express();
this.app
.use(bodyParser.json())
.get("/", (): void => {
throw new Error("Error from UserRoute class");
})
.use((_: Request, res: Response): void => {
console.log("Requested route not found");
res.status(404)
.send({ error: "Not found" });
})
.use((err: any, _: Request, res: Response): void => {
console.error("Unexpected error: ", err.stack);
res.status(500)
.send({ error: "An unexpected error occured" });
});
}
public start(): void {
this.app.listen(App.port, (): void => {
console.log("Server started!");
});
}
}
404 有效,但是当我在 http://localhost:8080/ 使用 Postman 发出请求时,我得到以下响应正文:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Error: Error from UserRoute class<br>
at E:\Programming\leslie\server\build\app.js:12:19<br>
at Layer.handle [as handle_request] (E:\Programming\leslie\server\node_modules\express\lib\router\layer.js:95:5)<br>
at next (E:\Programming\leslie\server\node_modules\express\lib\router\route.js:137:13)<br>
at Route.dispatch (E:\Programming\leslie\server\node_modules\express\lib\router\route.js:112:3)<br>
at Layer.handle [as handle_request] (E:\Programming\leslie\server\node_modules\express\lib\router\layer.js:95:5)<br>
at E:\Programming\leslie\server\node_modules\express\lib\router\index.js:281:22<br>
at Function.process_params (E:\Programming\leslie\server\node_modules\express\lib\router\index.js:335:12)<br>
at next (E:\Programming\leslie\server\node_modules\express\lib\router\index.js:275:10)<br>
at E:\Programming\leslie\server\node_modules\body-parser\lib\read.js:130:5<br>
at invokeCallback (E:\Programming\leslie\server\node_modules\raw-body\index.js:224:16)</pre>
</body>
</html>
【问题讨论】:
标签: node.js typescript express