Reputation: 3190
Sometimes I find myself writing the following code:
if (result.status == 200) {
return result.json()
} else {
return result.json().then(res => Promise.reject(res))
}
If the status is any other than 200 then the result will contain an error message which I would like to return. (This is part of a api.js script)
Is there a better way to "inverse" the .json() promise?
I thought of maybe something like this:
return Promise.reject(result.json)
Is there a way for me to do something like that? I am expecting the successful result of result.json to be the error object in the catch route.
Upvotes: 2
Views: 183
Reputation: 203
return result.json().then(res=>{
if(result.state!==200) return Promise.reject(res);
return res;
});
In my case I prefer the Promise.reject
info: Promise.reject vs throw Error
Upvotes: 0
Reputation: 23029
Well this looks a little weird, I would go with this approach
return result.json().then(json => {
if (result.status === 200) {
return json;
}
throw new Error(`Failed with ${json}`);
});
===
, using ==
can bring some issuesUpvotes: 1