如何妥善处理快递中的承诺拒绝

时间:2019-04-03 20:51:40

标签: express promise es6-promise express-router

我有以下快递员

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)

在我的应用中,我计划有几个控制器,它们使用promise来呈现结果

我不想每次都重复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可能是一项繁琐的任务,我希望有一个更聪明的解决方案。

您有什么想法吗?

2 个答案:

答案 0 :(得分:1)

在路由中使用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);
});

答案 1 :(得分:0)

因此,如果您真的想在每条路线上进行处理,这就是处理承诺拒绝的方法。

这也是它的单一班轮ES6版本。

代码

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

尽管像您所问的那样,最简单的方法是在index.js或app.js上使用流程来监听unhandledRejection

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

相关问题