请求返回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
相关产品推荐
相关产品推荐

