承诺和错误处理中间件

ExpressJS: Promises and Error Handling middleware

本文关键字:中间件 处理 错误 承诺      更新时间:2023-09-26

我定义了一些错误处理中间件和一个返回承诺的路由。但是当promise给出错误时,我必须在每个promise之后手动添加.catch(err => next(err))。虽然这不是问题,但对于ExpressJs来说,查看路由是否返回承诺并自动调用错误处理中间件不是很明智吗?

我当前的缩短代码:

// errorHandlers.js
function sequelizeValidationError (err, req, res, next) {
  if (err.name && err.name == 'SequelizeValidationError')
    res.status(400).send(err.errors)
  else next(err)
}
// auth.js
router.post ('/register',  middleware.isNotAuthenticated, (req, res, next) => {
  const { email, password, name } = req.body;
  return models.User.find({where : { email }}).then(user => {
    if (user) {
      if (user.password == password) sendToken(user.id, res);
      else res.sendStatus(401);
    } else {
      return models.User.create({
        email, password, name
      }).then(user => {
        sendToken(user.id, res);
      })
    }
  }).catch(next)
})
// index.js
router.use('/auth', require('./auth'))
router.use(errorHandlers.sequelizeValidationError)

例如,目前我可能忘记在一个地方写catch,服务器就会失败。

我错过什么了吗?我怎样才能避免每次都输入catch ?

这已经被归档了。

我已经归档了一个重复的bug

到目前为止,最好的办法似乎是使用换行函数。

请参阅@robertklep的评论。如果不使用route-params, promise-express-router可能有用。express-co似乎是一个wrap函数+更多基于生成器的优点