express如何在入口文件中处理所有的异常
 发布于 8 年前  作者 silenceboychen  4164 次预览  最后一次回复是 8 年前  来自 问答 

在express中使用async/await来控制异步流程,为了防止异常写了很多try/catch,不知道express能否在入口文件中处理所有程序执行过程中抛出的异常。

2 回复
zengming00

本楼正解

function ar(cb: (req: express.Request, res: express.Response, next: Function) => any) {
  return function (req: express.Request, res: express.Response, next: Function) {
    cb(req, res, next).catch((error: any) => {
      next(error);
    });
  }
}

router.get('/', ar(async function(req, res){
// 哈哈
}));