3

我有以下快递控制器

class ThingsController {

  static async index(req, res, next) {
    try {
      const things = await Thing.all();
      res.json(things);
    } catch(err) {
      next(err);
    }  
  }
}

和路由器

router.route('/things').get(ThingsController.index)

在我的应用程序中,我计划有几个控制器使用承诺来呈现结果

我不想每次都重复 try/catch 块

我的第一个解决方案是将这个逻辑提取到处理承诺拒绝函数中:

const handlePromiseRejection = (handler) =>

  async (req, res, next) => {
    try{
      await handler(req, res, next);
    } catch(err) {
      next(err);
    };
  };

现在我们可以从 ThingsController.index 中删除 try/catch 块,并且需要将路由器更改为:

router.route('/things')
  .get(handlePromiseRejection(ThingsController.index))

但是handlePromiseRejection在每条路线上添加可能是一项繁琐的任务,我希望有更聪明的解决方案。

你有什么想法?

4

2 回答 2

6

在路由中处理错误的正常方法async/await是捕获错误并将其传递给catch all错误处理程序:

app.use(async (req, res) => {
  try {
    const user = await someAction();
  } catch (err) {
    // pass to error handler
    next(err)
  }
});

app.use((err, req, res, next) => {
  // handle error here
  console.error(err);
});

使用express-async-errors包,您可以简单地throw(或不担心error从某些功能中抛出)。来自文档:Instead of patching all methods on an express Router, it wraps the Layer#handle property in one place, leaving all the rest of the express guts intact.

用法很简单:

require('express-async-errors'); // just require!
app.use(async (req, res) => {
  const user = await User.findByToken(req.get('authorization')); // could possibly throw error, implicitly does catch and next(err) for you

  // throw some error and let it be implicitly handled !!
  if (!user) throw Error("access denied");
});

app.use((err, req, res, next) => {
  // handle error
  console.error(err);
});
于 2019-04-04T11:18:00.517 回答
0

所以,如果你真的想处理每条路线,这就是你处理承诺拒绝的方式。

这也是它的一个单一的 ES6 版本。

代码

const handlePromiseRejection = (handler) => (req, res, next) => handler(req, res, next).catch(next)

unhandledRejection虽然就像你问的那样,最简单的方法是在你的 index.js 或 app.js 上使用进程来收听

process.on("unhandledRejection", (error, promise) => {
  console.log("Unhandled Rejection at:", promise, "reason:", reason);
  // Application specific logging, throwing an error, or other logic here
});

来自Node.js

于 2019-04-04T01:49:27.400 回答