我有以下提取功能
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]
,而no不能访问错误数组。这是我期望在回复中返回的内容
{
"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
。
关于javascript - 当响应返回适当的错误消息React时处理提取错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55923947/