【问题标题】:Express error handling in promises在 Promise 中表达错误处理
【发布时间】:2017-10-26 11:03:48
【问题描述】:

我在 express 和 Promises 中遇到错误。

我正在尝试用最好的方法来处理错误,在我的应用程序中创建一个标准的方法。

但是,我遇到了一个问题:

validate(req.body)
.catch(e => next(new APIError(400, e)))
.then(validatedbody => searchdatabase(validatedbody))
.then(dbResult => validate(dbResult))
.catch(e => next(new APIError(500, e)))
// results from db should always be valid
.then(validatedDbResult => res.json(validatedDbResult))

如果正文错误,我们应该停止并发送错误,错误将使用错误处理中间件发送,但是由于promise的工作原理,它也会继续下一步(在数据库中搜索) .

我该怎么办? 我是否首先正确处理错误?

非常感谢, 吉尔索

【问题讨论】:

  • APIError 中的命名参数?我认为这行不通。
  • 是的,纠正它,这是一个例子,它不是我的实际代码

标签: node.js express error-handling promise


【解决方案1】:

只需重新抛出错误,并且仅在链的最末端处理它:

validate(req.body)
.catch(e => { throw new APIError(400, e); })
.then(validatedbody =>
  searchdatabase(validatedbody)
  .then(validate)
  .catch(e => { throw new APIError(500, e); })
)
.then(validatedDbResult => res.json(validatedDbResult),
      next)

【讨论】:

  • 如果我重新抛出错误,它的状态将在使用您的代码的第二次抛出时改变,不是吗?
  • @Giltho 不,这就是为什么我嵌套了第二个catch 以仅捕获来自searchdatabasevalidate 的拒绝:-)
  • 哦,它是嵌套的,没看到,好吧,我想这会起作用,谢谢!!
猜你喜欢
  • 2019-02-17
  • 2016-09-29
  • 2019-01-05
  • 2016-04-20
  • 2016-06-08
  • 1970-01-01
  • 2015-06-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多