fetch: Ablehnen, Versprechen mit JSON-Objekt Fehler

Habe ich eine HTTP-API gibt JSON-Daten sowohl bei Erfolg und bei Misserfolg.

Beispiel scheitern würde wie folgt Aussehen:

~  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"
}

Was ich erreichen will in meinem JavaScript-code ist so etwas wie dieses:

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
   }
Du meinst json Methode gibt eine Promise?
Ja, als pro die fetch spec aus der Arbeitsgruppe: fetch.spec.whatwg.org/#concept-body-consume-body

InformationsquelleAutor jbaiter | 2015-04-06

Schreibe einen Kommentar