ExpressJS: Promises and Error Handling middleware

旧巷老猫 提交于 2019-12-11 01:13:37

问题


I have some error handling middleware defined and a route returning a promise. But when that promise gives an error, I have to manually append .catch(err => next(err)) after every promise. While its not a problem, isn't it sensible for ExpressJs to see if a route returns a promise and if so call the error handling middleware automatically.

My current shortened code:

// 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)

For example, currently I could have forgot to write catch at one place and the server would have failed.

Am I missing out on something? How can I avoid having to type the catch every time?


回答1:


This is already filed.

I had filed a duplicate bug

As of now the best bet seems to be to use a wrap function .

Also see @robertklep 's comment above. promise-express-router may be useful if you donot use route-params . express-co seems to be a wrap function + more generator-based goodness



来源:https://stackoverflow.com/questions/38080111/expressjs-promises-and-error-handling-middleware

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!