简体   繁体   English

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

[英]How to handle errors globally using co in express

I am new to nodejs and co. 我是nodejs和co的新手。 I am using co in express like below, since it is more like the async await I am used to in c# and I think the code is more readable. 我正在使用co in express,如下所示,因为它更像是我在c#中习惯的异步等待,我认为代码更具可读性。

(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));
    }

The problem is that everytime I call co, I have to handle the exception in the catch function. 问题是每次我调用co时,我都必须在catch函数中处理异常。 I would like to handle exceptions globally instead, in a middleware perhaps. 我想在全球范围内处理异常,也许是在中间件中。 But as far as I know, co swallows exceptions that are not handled, so I have to handle catch in every call to co. 但据我所知,co吞下了未处理的异常,因此我必须在每次调用co时处理catch。

One possible solution I came up with was to wrap co in a function that automatically handles the exceptions in the catch function and use that wrapped function instead. 我想出的一个可能的解决方案是将co包装在一个函数中,该函数自动处理catch函数中的异常并使用该包装函数代替。 Something like: 就像是:

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

Is there a better or more standard way? 有更好或更标准的方式吗?

You can use standard express error handler width this small lib : 你可以使用标准的快速错误处理程序宽度这个小的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);
  };
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM