简体   繁体   English

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

[英]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. 我想要做的是捕获错误消息,并从JSON响应中获取错误消息。 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. 我希望在我的第二个console.log中的表单上得到响应,但是以某种方式在第一个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? 另外,即使API密钥不存在,为什么响应在第一个实例中仍给我“确定”?

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? 当响应应该已经是JSON格式时,为什么还要在第二个实例中返回rsp.json()以获得正确的JSON?

The rsp in the first then-block is a response object, not the data returned by the backend. 第一个then块中的rsp是响应对象,而不是后端返回的数据。 The response object doesn't have a stat field, so the value of it cannot be "ok". 响应对象没有stat字段,因此其值不能为“ ok”。 You should probably check for rsp.ok or rsp.status instead. 您可能应该改为检查rsp.okrsp.status

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. 在第二个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);
  });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在获取响应转换为json时捕获错误并执行某些操作? - how to catch the error in fetch response conversion to json and do something? 使用axios捕获来自404响应的错误消息或在javascript中获取 - catch error message from 404 response with axios or fetch in javascript 如何从Node发送自定义错误消息,并使用catch显示它? - How do I send a custom error message from Node, and display it with catch? 如何从ionic-native HTTP get方法获取json响应? - How do I fetch a json response from ionic-native HTTP get method? 来自响应 JSON 的 Axios 捕获错误未定义 - Axios catch error from Response JSON is undefined 如何通过then()将Fetch响应的JSON主体传递给Throw Error()? - How can I pass JSON body of Fetch response to Throw Error() with then()? 如何从帖子消息中获取响应 - How to fetch Response from Post Message 为什么要在`fetch`中触发`catch`取决于我在第一个`then`中返回响应的方式? - Why triggering `catch` in `fetch` depends on how I return a response in first `then`? 如何从 apiCall 获取响应以显示在我的组件中? - How do I fetch the response from an apiCall to display in my component? 如何从 fetch 请求中键入 Response 对象? - How do I type a Response object from a fetch request?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM