You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

请求返回400状态时Catch语句未生效的技术咨询

问题原因

fetch API的逻辑是:只有当请求**根本发不出去(比如断网、域名不存在)**时才会触发catch块。像400这类HTTP状态码,属于服务器已经收到请求并返回了响应,fetch会认为整个请求流程是成功的,所以不会抛出异常,后端返回的错误信息就会被解析到data变量里。

解决方法

在拿到响应后,先判断状态是否正常,手动抛出异常让catch捕获:

修改后的代码:

export const registerUser = formData => async dispatch => {
    try {
        const response = await fetch('http://localhost:5000/api/users', {
            method: 'POST',
            body: formData
        })

        // 新增判断:非2xx状态码则抛出错误
        if (!response.ok) {
            const errorData = await response.json();
            throw new Error(errorData.message || '提交失败');
        }

        const data = await response.json()
        console.log(data)

        dispatch({
            type: 'auth/setToken',
            payload: data.token
        })
    } catch (err) {
        console.log(err.message); // 这里就能拿到后端返回的"name、email不能为空"这类提示了
    }
}

也可以直接根据状态码范围判断:

if (response.status >= 400 && response.status < 600) {
    const errorData = await response.json();
    throw new Error(errorData.message);
}

这样当后端返回400状态码时,会触发手动抛出的异常,进入catch块处理业务错误,符合你的预期。

内容的提问来源于stack exchange,提问作者Yash Sharma

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 01:32:09