通常,我有类似如下的Axios调用:
api.post('/users/add', (req, res, next) => {
Users.create(req.body).then(userResult => {
// misc code here
return res.json(userResult)
}).catch((err, req, res, next) => {
if (err) {
// handle the error by sending to the application error handler
next(err);
}
});
});
我遇到的问题是,如果错误是顺序化的验证错误,则req、res和next似乎不存在。因此,我在IF中添加了一个检查,如下所示:
if (err) {
if (err instanceof Sequelize.ValidationError) {
// i've tried a lot here and am stuck as to what to do
} else {
// handle other errors
}
}
一旦进入内部IF,我就可以很好地检查错误,但我不知道如何才能将响应返回给调用浏览器。我也不能调用next()并将错误冒泡到我的常规错误处理程序中,因为它无法识别next()。如果可以的话,我通常在req或res中使用的项目是不可用的。
我已经浏览了Sequelize网站上的所有文档,仔细研究了问题队列,在stackoverflow上搜索了此处,似乎找不到同样的问题。因此,我假设解决方案是一些简单的东西,只是我知识上的差距。请给我开导一下。我如何才能让它浮现到我的通用错误处理程序中,或者从这里向浏览器返回一个响应?
发布于 2018-10-11 08:25:17
不应在catch中重新定义req
、res
和next
。它们可以从父作用域访问,但是通过将它们包含在catch中,它们将是未定义的,因为then/catch将只有一个参数。
/* create a POST route. for /users/add requests it will
call a function passing in req, res, next() */
api.post('/users/add', (req, res, next) => { // this syntax creates an "arrow function"
/* note that it's probably a bad idea to just
pass in the request.body without sanitizing */
return Users.create(req.body) // call Sequelize and get a Promise
.then((userResult) => { // success, userResult will be the new user
return res.json(userResult); // use res.json() to send to client
})
.catch((err) => { // create failed
return next(err); // pass the err along to next()
});
});
如果您想用async/await
编写相同的代码,它允许您以同步语法编写异步代码。当您添加async
时,该函数将自动返回一个Promise。使用await
将等待承诺来解决(或抛出错误),而不会进入缩进地狱(在本例中是用户创建的结果)。
api.post('/users/add', async (req, res, next) => {
try {
const user = await Users.create(req.body);
return res.json(userResult);
} catch (err) {
return next(err);
}
});
https://stackoverflow.com/questions/52749101
复制相似问题