简体   繁体   中英

How do I catch an error message from JSON fetch response?

Consider the code below:

fetch('https://api.flickr.com/services/rest/?method=flickr.photos.search' +
    '&api_key=thiskeyshouldgivemeanerror&text=dog&format=json' +
    '&per_page=24&nojsoncallback=1')
    .then(function(rsp) {
        // Gives "Response {type: "cors", url: "https://api.flickr.com/services/rest/
        // ?method=flick…text=dog&format=json&per_page=24&nojsoncallback=1",
        // redirected: false, status: 200, ok: true, …}"
        console.log(rsp);
        if(rsp.stat !== "ok") {
            throw new Error(rsp.message);
        }
        else {
            return rsp.json();
        }
    })
    .then(function(rsp) {
        // Gives "{stat: "fail", code: 100, message: "Invalid API Key (Key not found)"}"
        // if no error is thrown.
        // Exactly what I want in the first instance!
        console.log(rsp);
    })
    .catch(function(err) {
        alert("Something went wrong. " + err);
    });

What I want to do is to catch an error with the error message I should get from the JSON response. I expect to get a response on the form it looks in my second console.log, but somehow the response does not look like that in the first console.log. How do I get the response I want in the first instance?

Also, why does the response give me "ok" in the first instance, even though the API key does not exist?

And why do I have to return rsp.json() to get the correct JSON in the second instance when the response should already be in JSON format?

The rsp in the first then-block is a response object, not the data returned by the backend. The response object doesn't have a stat field, so the value of it cannot be "ok". You should probably check for rsp.ok or rsp.status instead.

Check response object reference

In the second then-block you could do some checks based on the JSON data returned by the backend, and then throw an error if needed.

fetch(url)
  .then(function(response) {
    if(!response.ok) {
      throw new Error("not ok");
    }
    return response.json()
  })
  .then(function(result) {
    if(result.stat === "fail") {
      throw new Error(result.message);
    }

    // Everything should be ok, process the result here

  })
  .catch(function(err) {
    alert(err);
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM