
Axios 在请求失败(如状态码 400)时不会自动抛出响应体,而是将完整错误对象(含 response.data)封装在 error.response 中;需通过 err.response.data 显式访问后端返回的 JSON 内容。
axios 在请求失败(如状态码 400)时不会自动抛出响应体,而是将完整错误对象(含 `response.data`)封装在 `error.response` 中;需通过 `err.response.data` 显式访问后端返回的 json 内容。
当使用 Axios 发起请求并收到 HTTP 错误状态码(如 400 Bad Request)时,它不会像成功响应那样直接将 res.data 暴露给开发者——而是将整个响应信息包裹在 error.response 属性中。若未正确解构该对象,就容易只看到形如 [AxiosError: Request failed with status code 400] 的提示,而丢失后端返回的关键业务错误信息(例如 "Email already exists.")。
✅ 正确做法是在 catch 块中检查 error.response 是否存在,并安全读取其嵌套结构:
const handleSignup = async () => {
try {
setIsLoading(true);
const res = await axios({
url: 'http://10.0.2.2:8080/signup',
method: 'POST',
data: { name, email, password },
});
Alert.alert(res.data.message);
} catch (err: unknown) {
// 类型守卫:确保 err 是 AxiosError 且包含 response
if (axios.isAxiosError(err) && err.response) {
const errorMsg = err.response.data?.data?.message || '未知错误,请重试';
Alert.alert('注册失败', errorMsg);
console.error('API 错误详情:', err.response.data);
} else {
Alert.alert('网络错误', '无法连接到服务器');
console.error('请求异常:', err);
}
} finally {
setIsLoading(false);
}
};
? 关键注意事项:
- ❌ err.message 或 err.toString() 仅返回 Axios 错误摘要,不含业务数据;
- ✅ err.response.data 才是后端 res.status(400).json({...}) 实际返回的原始 JSON 对象;
- ? 务必进行空值检查(如 err.response?.data?.data?.message),避免因响应结构不一致导致运行时崩溃;
- ? 推荐搭配 axios.isAxiosError() 类型断言(需安装 @types/axios),提升 TypeScript 安全性;
- ? 若服务端返回格式统一(如始终为 { success: boolean; message?: string; errors?: any }),可封装通用错误处理器复用逻辑。
通过以上方式,你不仅能准确展示“邮箱已存在”等用户友好的提示,还能为调试提供完整的错误上下文,显著提升前端健壮性与体验一致性。











