Express错误处理:向前端发送消息

3

我在处理认证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
    })
}

还有另一种方法可以在Express的错误处理程序中设置本地变量,然后在Vue中稍后访问它们吗? - sevan1028
2个回答

3

对于那些有帮助的人,我找到了这个答案。被捕获的错误具有响应变量。这是通过express send命令发送数据的位置。请参见以下前端代码的更正:

login (e) {
    e.preventDefault();
    UserService.login(this.username, this.password) //this is simple axios post call 
    .catch((err) => {
         this.loginStatus = err.response.data.message
         return
    })
}

0

我认为你需要添加:

Throw new Error()

替代

Throw Error

如果您正在进行异步调用,可以这样做:
app.get('/', function (req, res, next) {
  fs.readFile('/file-does-not-exist', function (err, data) {
    if (err) {
       next(err) // Pass errors to Express.
    } else {
       res.send(data)
    }
  })
})

代码应该长这样:

router.post('/login', (req, res, next) => {
   throw new Error('this is the worst error ever')
})

检查这个在 express 文档 中。

新的Error()和Error()不应该有区别,因为应用程序的那部分是正常工作的。 - sevan1028

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接