J'ai une API HTTP qui renvoie des données JSON à la fois en cas de succès et en cas d'échec.fetch: rejeter la promesse avec l'objet d'erreur JSON
Un échec exemple ressemblerait à ceci:
~ ◆ 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"
}
Ce que je veux réaliser dans mon code JavaScript est quelque chose comme ceci:
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
}
Vous voulez dire 'méthode json' retourne un' Promise'? – thefourtheye
Oui, selon la spécification 'fetch' du groupe de travail: https://fetch.spec.whatwg.org/#concept-body-consume-body – jbaiter