通常,我的 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);
}
});
});
我遇到的问题是,如果错误是 Sequelize 验证错误,则 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 上进行了搜索,但似乎找不到相同的问题。因此,我认为解决方案很简单,只是我的知识空白。请赐教。我如何让它冒泡到我的一般错误处理程序或从这里向浏览器返回响应?
最佳答案
您不应在 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
将等待 Promise 解决(或抛出错误)而不会进入缩进 hell (在这种情况下是用户创建的结果)。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);
}
});
关于node.js - Axios + Sequelize ValidationError = Promise catch block 中没有请求或响应对象?如何处理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52749101/