【发布时间】:2020-12-04 02:36:09
【问题描述】:
我在后端有一个 API,它发送状态 201 在成功调用的情况下,如果有
提交数据的任何错误都会发送状态422(无法处理的实体),并带有如下的json响应:
{
"error": "Some error text here explaining the error"
}
此外,它还会发送404,以防 API 由于某种原因无法在后端工作。
在前端,我使用以下代码获取响应并根据响应状态代码执行成功或错误回调:
fetch("api_url_here", {
method: 'some_method_here',
credentials: "same-origin",
headers: {
"Content-type": "application/json; charset=UTF-8",
'X-CSRF-Token': "some_token_here"
}
})
.then(checkStatus)
.then(function json(response) {
return response.json()
})
.then(function(resp){
successCallback(resp)
})
.catch(function(error){
errorCallback(error);
});
//status function used above
checkStatus = (response) => {
if (response.status >= 200 && response.status < 300) {
return Promise.resolve(response)
} else {
return Promise.reject(new Error(response))
}
}
successCallback 函数能够在状态代码为201 的情况下以正确的 JSON 格式接收响应,但是当我尝试在errorCallback (status: 422) 中获取错误响应时,它会显示类似这样的内容(在控制台中记录响应):
Error: [object Response]
at status (grocery-market.js:447)
当我尝试console.log 错误响应,然后像这样将其包装在new Error() 中时,
checkStatus = (response) => {
if (response.status >= 200 && response.status < 300) {
return Promise.resolve(response)
} else {
console.log(response.json()) //logging the response beforehand
return Promise.reject(new Error(response.statusText))
}
}
我在控制台中得到以下承诺([[PromiseValue]] 属性实际上包含我需要的错误文本)
有人可以解释为什么这仅在错误情况下发生,即使我在错误和成功情况下都调用response.json()?
我怎样才能以干净的方式解决这个问题?
编辑:
我发现如果我在错误响应上创建另一个 json() 承诺,我就能得到正确的错误:
fetch("api_url_here", {
method: 'some_method_here',
credentials: "same-origin",
headers: {
"Content-type": "application/json; charset=UTF-8",
'X-CSRF-Token': "some_token_here"
}
})
.then(checkStatus)
.then(function json(response) {
return response.json()
})
.then(function(resp){
successCallback(resp)
})
.catch(function(error){
error.json().then((error) => { //changed here
errorCallback(error)
});
});
但是为什么在错误情况下我必须在响应中调用另一个.json()?
【问题讨论】:
-
Response.json() 是异步的,因此您可能希望使 checkStatus 异步并等待响应
-
@SørenEriksen 是的,我明白这一点,但在 checkStatus 中获取响应可能不是最干净的方法。我这样做只是为了事先检查发生了什么。
标签: javascript reactjs http error-handling fetch