首页 > 解决方案 > 如何在 saga try catch 失败时接收 json 返回消息?

问题描述

我有 saga try catch 的 axios 请求。但是,catch(err) 返回消息就像

Error: Request failed with status code 400

我想显示 res.state(400).json(errors) 发送的来自服务器的错误消息。在开发控制台 -> 网络上,我清楚地看到我的 JSON 文件已返回。

如何访问 catch(err) 块内返回的 JSON?

标签: reactjsredux-saga

解决方案


catch您可以使用(块或函数 - 取决于您是否使用try/catch或 Promise API)在 axios 中捕获错误。您可以使用 访问失败的响应数据error.response

下面是一个useEffect从端点获取数据并处理错误的钩子示例。

useEffect(() => {
    axios
      .get("https://your-domain/error")
      .then((response) => console.log("Response", response.body))
      .catch((error) =>
        console.log(`HTTP Status Code: ${error.response.status}; data: ${JSON.stringify(error.response.data)}`)
      );
  }, []);

端点本身是简单的 Express 端点,定义如下:

app.get("/error", (req, res) => {
  console.log("error");
  res.status(404).json({ error: "Not found" });
});

它返回带有 404 状态代码和{error: "Not found"}正文的响应。


推荐阅读