【发布时间】:2017-04-12 12:42:13
【问题描述】:
关于以下 TypeScript 代码:
app.get('/test_feature', function (req: Request, res: Response) {
throw new Error("This is the bug");
});
app.use(logErrors);
function logErrors (err: Error, req: Request, res: Response, next: NextFunction) {
console.log(err);
mongoDal.log(err.message, err);
next(err);
}
在这里,我在请求处理程序中抛出了一个错误,它按预期触发了 logErrors 函数。
然后,我将代码更改为使用异步函数:
app.get('/test_feature', async function (req: Request, res: Response) {
throw new Error("This is the bug");
await someAsyncFunction();
});
现在,因为我的函数是异步的,错误以某种方式被 Express 的默认错误处理程序处理,所以我的自定义错误处理程序没有被访问,也没有到达 Node 默认错误处理程序:
process.on('uncaughtException', function (err: Error) {
try {
console.log(err);
mongoDal.log(err.message, err);
} catch (err) {
}
});
当异步函数中发生错误时,如何使我的“logErrors”函数到达?我想要一个通用的解决方案,而不是在每个请求处理程序中尝试/捕获。
【问题讨论】:
标签: javascript express typescript error-handling async-await