99
rated 0 times
[
100]
[
1]
/ answers: 1 / hits: 67253
/ 9 Years ago, mon, april 6, 2015, 12:00:00
I have an HTTP API that returns JSON data both on success and on failure.
An example failure would look like this:
~ ◆ http get http://localhost:5000/api/isbn/2266202022
HTTP/1.1 400 BAD REQUEST
Content-Length: 171
Content-Type: application/json
Server: TornadoServer/4.0
{
message: There was an issue with at least some of the supplied values.,
payload: {
isbn: Could not find match for ISBN.
},
type: validation
}
What I want to achieve in my JavaScript code is something like this:
fetch(url)
.then((resp) => {
if (resp.status >= 200 && resp.status < 300) {
return resp.json();
} else {
// This does not work, since the Promise returned by `json()` is never fulfilled
return Promise.reject(resp.json());
}
})
.catch((error) => {
// Do something with the error object
}
More From » promise