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

在ReactJS+Axios+NodeJS技术栈下如何渲染API返回的错误响应?

问题解决方案

核心原因

你遇到的无法捕获422错误的问题主要是两个原因:

  • axios默认仅对2xx区间的状态码执行正常返回逻辑,422属于客户端错误状态码,会直接抛出异常,你当前的代码没有对异步请求做异常捕获
  • 后端返回的错误字段是erro,注意不要和你预期的error混淆

修复步骤

1. 新增错误提示状态

在React组件内新增状态存储错误信息,用于页面渲染:

const [errorMsg, setErrorMsg] = useState('');

2. 给axios请求加异常捕获

修改handleSubmit逻辑,用try/catch包裹请求代码,捕获非2xx状态的错误返回:

async function handleSubmit() {
  try {
    // 每次提交前清空之前的错误
    setErrorMsg('')
    const response = await axios.post("http://localhost:3001/usuario/register",{
        email,
        name,
        password,
      },{
        headers: { "Content-Type": "application/json" },
      }
    );
    console.log(response.data);
    const { data } = response;
    return data
  } catch (err) {
    // 判定是后端返回的响应错误
    if (err.response) {
      // 从response.data中取后端返回的erro字段
      setErrorMsg(err.response.data.erro)
    } else {
      // 网络错误等其他异常
      setErrorMsg('网络异常,请稍后重试')
    }
  }
}

3. 页面渲染错误信息

在组件的return模板中添加错误提示的渲染逻辑:

return (
  <div>
    {/* 错误提示 */}
    {errorMsg && <p style={{color: 'red'}}>{errorMsg}</p>}
    {/* 原有表单代码 */}
    ...
  </div>
)

后端逻辑校验补充

如果修改前端后还是拿不到错误,检查后端逻辑:你的密码校验逻辑需要在创建Usuario实例时主动抛出InvalidArgumentError才会进入catch分支返回422,确保校验失败时确实有抛出对应错误。

内容的提问来源于stack exchange,提问作者Guilherme Iuri

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 16:39:05