node.js - 节点 | 错误中间件不处理异常
问题描述
我们的后端应用是基于node和TS的,我们使用了nightJS库。不幸的是,当我尝试创建和错误中间件时,同时使用:
this.app.use((error:Error, req: Request, res: Response, next: NextFunction) => {
console.log("error captured ");
next(error);
});
或者:
@ClassErrorMiddleware(logErrorAndStop)
但是当我在控制器中抛出错误时:
@Get("table")
private async getAssetsForTable(req: UserRequest, res: Response) {
throw Error("table error");
}
我预计该错误将在其中一个中间件中被捕获,但线程却堆积在错误上:
2021-03-14T15:09:20.060Z error: unhandled error Error: table error
并且服务器不返回任何响应(客户端正在等待,可能直到超时)。
我也尝试过这样的事情:
this.app.use((req: Request, res: Response, next: NextFunction) => {
try {
console.log("middleware test");
next();
}catch (ex){
next(ex);
}
});
为每个请求打印了“中间件测试”字符串,但随后线程仍然如前所述被卡住。
任何想法为什么?
解决方案
快速中间件不处理未处理的拒绝。
例如
import express from 'express'
const app = express();
app.use(someBeforeHookMiddleware) // Middleware that are called before entering into the routes
app.get('/test1', (req, res, next) => {
throw new Error('Hello Unhandled') // This kind of error are Unhandled and can't be caught by Express Middleware
});
app.get('/test2', (req, res, next) => {
try {
const raiseSomeError = someErrorCausingFunction();
if(!raiseSomeError) next() // if no error in the above function simply pass to next handler without args to next()
} catch(error) {
next(error) // passing error here so Error middleware is activated in the chain
}
});
// Error handling middleware
app.use((err, req, res, next) => {
console.log('Oops !!, Error occured in req->res cycle ', error.message);
res.status(err.status).json({ error }); // Send back Error to the Frontend
})
推荐阅读
- firebase - Failing to write data to firestore using flutter and firebase
- vim - 类似笔记本的 Vim 和 IPython shell
- ipfs - Is it possible to share a folder for writes and updates between different IPFS nodes?
- python - 为什么我的输出没有大写 python?
- angular - 使用 Angular 7 导航时页面未正确加载
- postman - 无法使用来自automate.io 的webhook 将表单数据发布到应用程序
- android - 我在签名的 apk 中收到错误“WebViewFactory:没有这种方法”
- javascript - javascript中的简单货币转换
- angular - 调用异步验证器时,角度服务始终未定义
- python - 如何在 Django 帖子中添加评论