如何在 express 中使用 co 全局处理错误

How to handle errors globally using co in express

我是 nodejs 和公司的新手。我像下面这样在 express 中使用 co,因为它更像是我在 c# 中习惯的 async await,而且我认为代码更具可读性。

(req, res) => {
        co(function*(){
            var book = req.book;

            book.bookId = req.body.bookId;
            book.title = req.body.title;               
            book.read = req.body.read;

            yield book.save();

            res.json(book);
        }).catch(err => res.status(500).send(err));
    }

问题是每次我调用co时,我都必须在catch函数中处理异常。我想在全局范围内处理异常,也许在中间件中。但据我所知,co 吞下了未处理的异常,所以我必须在每次调用 co 时处理 catch。

我想到的一个可能的解决方案是将 co 包装在一个自动处理 catch 函数中的异常的函数中,然后改用该包装函数。类似于:

var myCo = function(genFunc){
   return co(genFunc)
          .catch(err => someGlobalErrorHandler(err))
};

是否有更好或更标准的方法?

您可以使用标准的快速错误处理程序宽度 small lib:

var co = require('co');

module.exports = function wrap(gen) {
  var fn = co.wrap(gen);

  if (gen.length === 4) {
    return function(err, req, res, next) {
      return fn(err, req, res, next).catch(next);
    }
  }

  return function(req, res, next) {
    return fn(req, res, next).catch(next);
  };
};