ExpressJS:承诺和错误处理中间件 [英] ExpressJS: Promises and Error Handling middleware
问题描述
我定义了一些错误处理中间件,并且路由返回了Promise.但是,当那个承诺产生错误时,我必须在每个承诺之后手动附加.catch(err => next(err))
.虽然这不是问题,但ExpressJ判断路由是否返回了诺言是否明智?如果是,则自动调用错误处理中间件.
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.
我当前的简化代码:
// 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
,并且服务器将发生故障.
For example, currently I could have forgot to write catch
at one place and the server would have failed.
我错过了什么吗?如何避免每次都要键入catch
?
Am I missing out on something? How can I avoid having to type the catch
every time?
推荐答案
这是已提交.
我提交了重复错误
到目前为止,最好的选择似乎是使用包装函数.
As of now the best bet seems to be to use a wrap function .
另请参见上面的@robertklep的注释.如果不使用route-params
, promise-express-router
可能会有用. express-co
似乎是一个包装函数+更多基于生成器的优点
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
这篇关于ExpressJS:承诺和错误处理中间件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!