如何在 saga try catch 失败时接收 json return 消息?

How to receive json return message in saga try catch when it fails?

我有 saga try catch for axios 请求。但是,catch(err) returns 消息就像

Error: Request failed with status code 400

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

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

您可以使用 catch 捕获 axios 中的错误(块或函数 - 取决于您是使用 try/catch 还是 Promise API)。您可以使用 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" });
});

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