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

React中fetch请求JSON并更新时如何捕获404错误?

解决React中PUT请求404时显示错误提示的问题

问题根源

fetch API 只有在网络层面失败(比如请求无法发送、断网)时才会触发catch,像404这类HTTP状态码错误不会自动进入捕获逻辑,这就是你之前用catch没生效的原因,必须手动检查响应状态。

修复代码

修改updateTemplate函数,先判断响应是否正常,再分别处理成功/失败场景,同时用try/catch覆盖所有可能的错误:

async function updateTemplate() {
  let item = {
    id: template.id,
    templateName: template.templateName,
    tags: template.tags,
  };
  console.warn("item", item);
  try {
    const result = await fetch(`http://localhost:8080/templates/${template.id}`, {
      method: "PUT",
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json",
      },
      body: JSON.stringify(item),
    });

    // 检查HTTP响应状态是否成功(状态码200-299)
    if (!result.ok) {
      if (result.status === 404) {
        setMessage("Update failed");
      } else {
        setMessage(`Update failed: ${result.statusText}`);
      }
      return;
    }

    // 响应正常时更新数据并提示成功
    const resp = await result.json();
    console.warn(resp);
    getTemplates();
    setMessage("Update successful"); // 修正拼写错误:succesful → successful
  } catch (err) {
    // 处理网络错误或JSON解析错误
    console.error("请求出错:", err);
    setMessage("Update failed");
  }
}

额外优化建议

  1. 修正拼写错误:原代码中"Update succesful"拼写错误,改为"Update successful"
  2. 统一异步写法:把getTemplates也改成纯async/await风格,避免混合then链:
async function getTemplates() {
  try {
    const result = await fetch("http://localhost:8080/templates");
    if (!result.ok) throw new Error("获取模板失败");
    const resp = await result.json();
    setTemplates(resp);
  } catch (err) {
    console.error("获取模板出错:", err);
  }
}
  1. 优化提示样式:根据消息类型切换颜色,失败时显示红色更直观:
<p style={{ color: message.includes("failed") ? "red" : "green", marginTop: "10px" }}>
  {message}
</p>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 13:41:13