I have an API on backend which sends status 201 in case of a successful call and if there's
any error with the submitted data it sends status 422 (Unprocessable Entity) with a json response like below:
{
"error": "Some error text here explaining the error"
}
Additionally it sends 404 in case API fails to work on back end for some reason.
On the front-end I'm using the below code to fetch the response and perform a success or error callback based on response status code:
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))
}
}
The successCallback function is able to receive the response in proper JSON format in case of status code 201 but when I try to fetch the error response in errorCallback (status: 422) it shows something like this (logging the response in console):
Error: [object Response]
at status (grocery-market.js:447)
When I try to console.log the error response before wrapping it in new Error() like this,
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))
}
}
I get the below promise in console (the [[PromiseValue]] property actually contains the error text that i require)
Can someone please explain why this is happening only in error case, even though I'm calling response.json() in both error and success case?
How can I fix this in a clean manner?
EDIT:
I found that if I create another json() promise on the error response I am able to get the correct error :
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)
});
});
But why do I have to call another .json() on the response in error case?
