javascript - 当响应返回适当的错误消息时处理 fetch 错误
问题描述
我有以下获取功能
request(url, options) {
return fetch(url, _.defaultsDeep(options || {}, defaultOptions))
.then(handleErrors)
.then(response => response.json())
.catch(error => handleFetchError(error));
}
该handleErrors
函数执行以下操作以检查响应是否失败...
function handleErrors(response) {
if (!response.ok) {
throw new Error(response.statusText);
}
return response;
}
我遇到的问题是 API 返回一个400
状态,还有一个带有相关错误消息的数组,但使用throw new Error(response.statusText);
只返回一些通用错误消息Error: [object Object]
,而不是访问错误数组。
这是我期望在响应中返回的
{
"status": 400,
"error": "Bad Request",
"errors": [
{ "defaultMessage": "Please check that your name contains only letters and is longer than two characters" }
]
}
我无权访问 API 服务器端,因此我无法在那里更改任何内容。
但是有没有一种方法可以让我抛出一个错误来捕获但也可以访问errors
响应中的数组?
编辑:
这handleErrors
是我收到的响应对象
{
"type": "default",
"status": 401,
"ok": false,
"statusText": "",
"headers": {
"map": {
"pragma": "no-cache",
"date": "Wed, 01 May 2019 07:44:40 GMT",
"x-content-type-options": "nosniff",
"x-frame-options": "DENY",
"content-type": "application/json;charset=ISO-8859-1",
"cache-control": "no-cache, no-store, max-age=0, must-revalidate",
"content-length": "53",
"x-xss-protection": "1; mode=block",
"expires": "0"
}
},
"url": "http://localhost:8080/login",
"_bodyInit": {},
"_bodyBlob": {}
}
当我抛出错误并尝试在参数中访问它时handleFetchError
只是error
一个空对象{}
解决方案
看起来您正在尝试抛出response.statusText
,但您的响应没有该属性。它有status
.
推荐阅读
- c++ - iOS 检查并创建文件夹 c++
- jenkins - Jenkins 多分支管道拉取请求
- augmented-reality - 将值连接到 Spark AR 中延迟补丁的持续时间参数
- typo3 - 当您的菜单是静态的时,是否可以在 TYPO3 中创建多语言站点?
- symfony - 如何通过多次提交测试表单
- android - 原因:java.lang.ClassNotFoundException:在路径上找不到类“com.example.aol.Application”:DexPathList 错误颤动
- android -
对于 WhatsApp 音频共享 - r - 表示 r 中具有不同线型的 SEM 的重要和非重要路径
- typescript - 打字稿允许在具有推断类型的变量上添加属性并在类型显式时抱怨
- python - Pytorch model.load 调用歧义