我在处理认证API调用时遇到了一些错误处理问题。当我从Express发送500状态码时,我的前端(例如Vue)仅捕获消息Request failed with status code 500 ,而不是更有助于诊断的信息,例如this is the worst error ever (在下面的示例中)。
在下面的示例中,当我从API调用“/post”时,我会抛出一个错误,该错误由自定义中间件处理。该中间件成功处理错误并向我的前端发送适当的状态,但我无法弄清楚如何发送有用的消息(例如,“this is the worst error ever”)/并在前端访问它们。
这是常见的用例吗? 我是否做错了任何明显的事情? 我发送的消息是否会出现在(err)参数中,还是需要添加一个resp参数?
'/login' 的 Express 路由
router.post('/login', (req, res, next) => {
throw Error('this is the worst error ever')
})
自定义 express 错误处理程序
app.use(function(err, req, res, next) {
res.status(err.status || 500).send({
error: {
status: err.status || 500,
message: err.message || 'Internal Server Error',
},
});
});
在Vue中处理API响应
login (e) {
e.preventDefault();
UserService.login(this.username, this.password) //this is simple axios post call
.catch((err) => {
this.loginStatus = err.message
return
})
}