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

时间:2018-08-10 11:33:50

标签: javascript json fetch-api

考虑以下代码:

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密钥不存在,为什么响应在第一个实例中仍给我“确定”?

为什么当响应应该已经是JSON格式时,为什么我必须返回rsp.json()才能在第二个实例中获得正确的JSON?

1 个答案:

答案 0 :(得分:2)

第一个then块中的rsp是一个响应对象,而不是后端返回的数据。响应对象没有stat字段,因此其值不能为“ ok”。您可能应该改为检查rsp.okrsp.status

选中response object reference

在第二个then块中,您可以根据后端返回的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);
  });