expressJS 承诺和错误处理

expressJS promise and error handling

我有一条路线,首先需要查询数据库,然后根据结果查询另一个 Web 服务,然后根据该结果呈现页面。 我已经制定了该流程并正在尝试找出错误处理。鉴于我与多个服务交谈,我试图在将错误返回给 express 之前解决错误。

这是路由代码的结构:

Models.Episode.findById(request.params.episodeID)
    .catch(function (error) {
        throw (throwjs.notFound());
    })
    .then(function (episode) {
        if (episode.getUser().id !== request.user.href) {
            return next(throwjs.unauthorized("You do not have access to this podcast"));
        }
        return doSomeOtherAsyncStuff();
    })
    .then(function (queryResponse) {
        renderPage();
    })
    .catch(function (error) {
        next(error);
    });

我的问题是第一个问题。我这次catch的目标是重新打包错误并停止执行并将错误发送给express中间件。

按照上面的写法,执行停止了,但是我的快速错误处理程序没有被调用。

我尝试将第一个捕获重写为

.catch(function(error){
     return next(error);
})

但这并不能解决问题。我找到的唯一解决方案是将捕获物移到最后。但是后来我失去了失败位置的上下文。

关于我做错了什么的任何线索? 谢谢,奥利维尔

毕竟这和我用的throwjs框架有关,我用错了

    throw (throwjs.notFound());

应该是

    throw (new throwjs.notFound());

...

我建议采用不同的方法,这样您就不必依赖长 运行 承诺链。使用以下方法,您已将授权和验证分离到单独的中间件,因为它们不一定是实际剧集处理程序本身的关注点。而且这种方式表达起来更地道。

一个额外的好处是您可以自由地将错误传递给错误处理程序,这样您就可以进一步将错误与路由处理程序分离。

function validateEpisode(req, res, next) {
  Models.Episode
    .findById(req.params.episodeID)
    .then(function(episode) {
      req.yourApp.episode = episode;
      next() // everything's good
    })
    .catch(function(error) {
      // would be better to pass error in next
      // so you can have a general error handler
      // do something with the actual error
      next(throwjs.notFound());
    });
}

function authUserByEpisode(req, res, next) {
  if (req.yourApp.episode.getUser().id !== req.user.href) {
    next(throwjs.unauthorized("You do not have access to this podcast"));
  }

  next(); // authorized
}

function episodeController(req, res) {
  // do something with req.yourApp.episode
}

app.get('/episode/:id', validateEpisode, authUserByEpisode, episodeController)