首页 > 解决方案 > 抛出错误给我 API 错误,而不是我写的

问题描述


使用 Fetch,我试图让我的代码返回我写的自定义错误消息,而不是来自 api 的响应错误消息。
在此示例中,我不想使用“自定义错误消息”,因为我得到“无法获取”。我只知道我是否尝试使用其他 API。有时它会起作用。
我究竟做错了什么?
export default function App() {

  const [loading, setLoading] = useState(true)
  const [api, setApi] = useState("")
  const [error, setError] = useState("")

  useEffect(() => {
    fetch("url")
    .then(res => {
      if(!res.ok){
        throw Error("CUSTOM ERROR MESSAGE")
      }
      return res.json()
    })
    .then(data => {
      setApi(data)
      setLoading(false)
    })
    .catch(error => {
      setError(error)
      setLoading(false)
    })
  }, [])

  console.log(error)

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      {
        loading === "" ? <h1>loading...</h1> : <h1>{api.name}</h1>
      }
      {
        error === "" ? "" : <h1>{error}</h1>
      }
      
    </div>
  );
}

标签: reactjsfetch

解决方案


推荐阅读