reactjs - 如何在 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?
解决方案
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"}
正文的响应。
推荐阅读
- java - 根据客户端请求将数据流式传输到 Web 套接字
- javascript - React 状态在其分配的变量发生变化时发生变化
- python - Can't read frame with webcam. Error -2147483638
- ansible - ansible Tower 安装后无法获取许可证列表
- php - mdbtools 和 unixodbc 的 odbc_connect 问题
- java - 如何在 Spring Boot 应用程序属性中动态获取 aws memcached 配置端点
- java - 性能:每次保存默认图像或对其进行编码
- c++ - 如何同时读取和写入文件
- javascript - Yup 表单的多个 date.min() 验证
- angular - 无法使用托管在 Azure 工件中的管道和外部库在 Azure 中安装 npm