【问题标题】:How to catch error when fetching json and updating it with fetch?获取 json 并使用 fetch 更新它时如何捕获错误?
【发布时间】:2022-10-12 22:13:30
【问题描述】:

当我在updateTemplate 函数中有PUT ERROR 404 not found 时,我希望这个setMessage 不显示。我用catch(err) 尝试过,但没有成功。

完整代码sn-p:

import "./App.css";
import React, { useEffect, useState } from "react";

function App() {
  const [templates, setTemplates] = useState([]);
  const [template, setTemplate] = useState({ templateName: "", tags: [] });
  const [message, setMessage] = useState("");

  useEffect(() => {
    getTemplates();
  }, []);

  async function getTemplates() {
    await fetch("http://localhost:8080/templates").then((result) => {
      result.json().then((resp) => {
        setTemplates(resp);
      });
    });
  }

  function selecTemplate(templateName) {
    let item = templates.find((t) => t.templateName === templateName);
    setTemplate(item);
    setMessage("");
  }

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

  const handleChange = (event) => {
    console.log(event.target);
    if (event.target.name === "name") {
      setTemplate({ ...template, name: event.target.value });
    } else {
      var tags = template.tags;
      switch (event.target.name) {
        case "tag0":
          tags[0] = event.target.value;
          break;
        case "tag1":
          tags[1] = event.target.value;
          break;
        case "tag2":
          tags[2] = event.target.value;
          break;
        default:
          break;
      }
      setTemplate({ ...template, tags: tags });
    }
  };

  return (
    <div className="App">
      <div className="container">
        <div className="table-responsive">
          <table className="table table-dark" border="1">
            <tbody>
              <tr>
                <td className="bg-info">Name</td>
                <td className="bg-info">Select template</td>
              </tr>

              {templates.map((item, i) => (
                <tr key={i}>
                  <td>{item.templateName}</td>

                  <td>
                    <button
                      className="btn btn-danger"
                      onClick={() => selecTemplate(item.templateName)}
                    >
                      Select
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        <div className="inputs">
          <input
            type="text"
            name="name"
            value={template.templateName}
            onChange={handleChange}
          />{" "}
          <br />
          <br />
          <input
            type="text"
            name="tag0"
            value={template.tags[0]}
            onChange={handleChange}
          />{" "}
          <br />
          <br />
          <input
            type="text"
            name="tag1"
            value={template.tags[1]}
            onChange={handleChange}
          />{" "}
          <br />
          <br />
          <input
            type="text"
            name="tag2"
            value={template.tags[2]}
            onChange={handleChange}
          />{" "}
          <br />
          <br />
          <button className="btn btn-danger" onClick={updateTemplate}>
            Update Template
          </button>
          <p style={{ color: "green", marginTop: "10px" }}>{message}</p>
        </div>
      </div>
      
    </div>
  );
}
export default App;

下面是我得到的错误的图像,当我得到它时,我想显示“更新失败”而不是“更新成功”:

【问题讨论】:

    标签: javascript reactjs json


    【解决方案1】:

    fetch() 仅在出现网络错误时自行引发错误,例如服务器无法响应。这是来自 mdn 的note

    当遇到网络错误或在服务器端配置错误的 CORS 时,fetch() 承诺会以TypeError 拒绝,尽管这通常意味着权限问题或类似问题——例如,404 并不构成网络错误。对成功的fetch() 的准确检查将包括检查承诺是否已解决,然后检查Response.ok 属性的值是否为真。

    对于其他类型的错误,例如 404,在您的情况下,您应该添加一个检查并自己抛出错误,然后捕获它,如下所示:

    async function updateTemplate() {
      let item = {
        id: template.id,
        templateName: template.templateName,
        tags: template.tags,
      };
      console.warn("item", item);
      await fetch(`http://localhost:8080/templates/${template.id}`, {
        method: "PUT",
        headers: {
          Accept: "application/json",
          "Content-Type": "application/json",
        },
        body: JSON.stringify(item),
      })
        .then((result) => {
          if (!result.ok) throw Error("Update failed"); // line I added
          return result.json();
        })
        .then((data) => {
          console.warn(data);
          getTemplates();
          setMessage("Update succesful");
        })
        .catch((error) => {
          console.log(error);
          setMessage("Update failed");
        });
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-07
      • 2023-01-11
      • 2016-10-30
      • 2019-05-22
      • 2018-03-31
      • 2018-09-28
      • 2014-11-18
      • 1970-01-01
      相关资源
      最近更新 更多