如何将Express后端错误传递至前端catch块并获取错误信息
如何在fetch的res.ok判断逻辑中获取后端404返回的错误消息?
问题背景
后端返回404状态码时,前端fetch的res.ok会变为false,我想知道能不能在检查res.ok的if语句中直接获取后端返回的错误消息?
当前后端代码
app.post('/recover_password', (req, res) => { const customer_has_account = true if (!customer_has_account) { return res.status(404).json('no account found with that email') } })
当前前端代码
fetch('/recover_password', { method: 'POST', body: /* ... */ }) .then(res => { if (!res.ok) { throw new Error(/* 这里能否传入后端返回的错误信息? */) } return res.json() }) .then(data => console.log(data)) .catch(err => { console.log(err) })
我已经知晓以下方案可行,但希望了解是否能实现上述在res.ok判断逻辑中直接获取错误消息的方式:
已知可行方案的后端代码
app.post('/recover_password', (req, res) => { const customer_has_account = true if (!customer_has_account) { return res.status(404).json({ error: 'no account with that email found '}) } })
已知可行方案的前端代码
fetch('/recover_password', { method: 'POST', body: /* ... */ }) .then(res => res.json()) .then(data => { if (data.error) throw new Error(data.error) }) .catch(err => console.log(err))
解答
完全可以实现,核心思路是在res.ok为false时,先解析后端返回的响应内容,再抛出包含错误消息的异常。因为fetch对于4xx状态码不会自动拒绝Promise,需要我们手动处理响应体的解析。
修改后的前端代码如下:
fetch('/recover_password', { method: 'POST', body: /* ... */ }) .then(async res => { if (!res.ok) { // 解析后端返回的错误内容 const errorMsg = await res.json(); throw new Error(errorMsg); } return res.json(); }) .then(data => console.log(data)) .catch(err => { console.log(err.message); // 输出:no account found with that email })
关键说明
res.json()返回的是Promise,所以需要用async/await或者链式then来获取解析后的结果- 如果后端返回的是纯文本而非JSON,改用
res.text()即可 - 这种方式既保留了通过
res.ok判断请求状态的逻辑,又能拿到后端返回的错误详情
内容的提问来源于stack exchange,提问作者dbzx10299
相关产品推荐
相关产品推荐

