【问题标题】:How do I catch an error message from JSON fetch response?如何从 JSON 获取响应中捕获错误消息?
【发布时间】:2019-01-18 00:24:35
【问题描述】:

考虑下面的代码:

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”?

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

【问题讨论】:

    标签: javascript json fetch-api


    【解决方案1】:

    第一个 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);
      });
    

    【讨论】:

      猜你喜欢
      • 2019-07-26
      • 2018-07-29
      • 1970-01-01
      • 1970-01-01
      • 2016-03-12
      • 2018-12-20
      • 2022-01-08
      • 2023-04-04
      • 1970-01-01
      相关资源
      最近更新 更多