javascript - expressJS promise 和错误处理

标签 javascript express error-handling promise catch-block

我有一条路线,首先需要查询数据库,然后使用结果查询另一个 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);
})

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

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

最佳答案

我建议采用不同的方法,这样您就不必依赖长时间运行的 promise 链。通过以下方法,您已将授权和验证与单独的中间件分离,因为它们不一定是实际情节处理程序本身的关注点。而且这种方法表达起来更惯用。

另一个好处是您可以自由地将错误传递给错误处理程序,以便进一步将错误与路由处理程序解耦。

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)

关于javascript - expressJS promise 和错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37750248/

相关文章:

javascript - 如何更改 `this` 关键字的行为

javascript - 如何聚焦输入并取消选择其中的文本

javascript - 如何正确实现 CORS (Access-Control-Allow-Origin)?

javascript - SAP UI5 - 如何根据行状态禁用 sap.m.Table Multiselect 表中的行

javascript - 为断言设置自定义错误消息 (Node.js)

node.js - HTTP2 的 Express 类型

javascript - JSON内容发布请求验证实践

angularjs - 如何在手机上使用 MEAN 应用程序

c#-4.0 - ASP.NET 4.0错误处理除500状态外不起作用

php - phpBB 500内部服务器错误,无日志输出