如何从 JSON 获取响应中捕获错误消息?

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

考虑以下代码:

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);
    });

我想做的是用我应该从 JSON 响应中得到的错误消息来捕获错误。我希望在我的第二个 console.log 中得到回复,但不知怎的,回复看起来不像第一个 console.log 中的那样。如何在第一时间得到我想要的回应?

此外,即使 API 密钥不存在,为什么响应一开始就给我 "ok"?

为什么我必须 return rsp.json() 在第二个实例中获得正确的 JSON 而响应应该已经是 JSON 格式?

第一个then-block中的rsp是响应对象,不是后台返回的数据。响应对象没有 stat 字段,因此它的值不能是 "ok"。您可能应该检查 rsp.okrsp.status

勾选response object reference

在第二个 then-block 中,您可以根据后端返回的 JSON 数据进行一些检查,然后在需要时抛出错误。

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);
  });