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

React代码状态码500时未显示错误的技术问题求助

问题原因及解决办法

你的代码里,当后端返回500状态码时,axios会直接触发catch块,根本不会执行你写的res.data.status === 500分支逻辑。这是因为axios默认将HTTP状态码≥400的响应判定为请求错误,直接跳转到catch处理。

另外注意:headers里的multipart/formData拼写错误,正确格式是multipart/form-data,这个问题可能导致请求本身异常,建议先修正。

解决方式一:修改axios的错误判定规则

给axios请求添加validateStatus配置,让它不把500状态码视为错误,这样所有状态码的响应都会进入then块,你就能正常判断状态码了:

try {
  const res = await axios({
    method: "post",
    url: `${landslide}`,
    data: formData,
    headers: {'Content-type': "multipart/form-data"},
    // 配置:允许所有状态码进入then块自行处理
    validateStatus: (status) => true
  });
  console.log("hello", res);
  if (res.data.status === 200) {
    swal("success", res.data.message, "success").then(function() {
      navigation("/landslide");
    });
  } else if (res.data.status === 500) {
    swal("warning", res.data.message, "warning").then(function() {
      navigation("/landslide");
    });
  }
} catch (error) {
  swal("warning", "please check your form's input", "warning").then(function() {
    navigation("/landslide-report");
  });
}

解决方式二:在catch块中处理500状态码

如果不想修改axios默认规则,可以在catch块里读取error.response获取后端返回的详细信息,判断状态码后针对性处理:

try {
  const res = await axios({
    method: "post",
    url: `${landslide}`,
    data: formData,
    headers: {'Content-type': "multipart/form-data"}
  });
  console.log("hello", res);
  if (res.data.status === 200) {
    swal("success", res.data.message, "success").then(function() {
      navigation("/landslide");
    });
  }
} catch (error) {
  // 优先处理后端返回的500错误
  if (error.response?.data?.status === 500) {
    swal("warning", error.response.data.message, "warning").then(function() {
      navigation("/landslide");
    });
  } else {
    // 处理其他请求异常
    swal("warning", "please check your form's input", "warning").then(function() {
      navigation("/landslide-report");
    });
  }
}

内容的提问来源于stack exchange,提问作者Priyanka Shakya

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 12:52:45