【问题标题】:how to catch the error in fetch response conversion to json and do something?如何在获取响应转换为 json 时捕获错误并执行某些操作?
【发布时间】:2019-01-22 19:53:32
【问题描述】:

我正在使用这个 fetch 请求,有时响应正常(200)但响应无法转换为 json。我不确定如何捕捉这个错误,我尝试过使用 try/catch 但无法确定这些子句的确切位置。我不是 javascript 专家,任何建议都将不胜感激!

fetch(url2, {
        method: 'POST',
        signal: signal,
      }).then(function(response) {
          console.log(response);
          console.log(response.url);
        return response.json();
      }).then(function(json) {
        var features = new ol.format.GeoJSON().readFeatures(json);
 }); 

这是我得到的响应和错误:

Response {type: "basic", url: "http://localhost:8080/geoserver/wfs?service=WFS&ve…27%20acres%3E%3D300&outputFormat=application/json", redirected: false, status: 200, ok: true, …}
qgis2web.js:416 http://localhost:8080/geoserver/wfs?service=WFS&version=1.1.0&request=GetFeature&typename=sde:parcels_slim_part_view&maxFeatures=1000&CQL_FILTER=county=%27Camden%27%20acres%3E%3D300&outputFormat=application/json

index.html#:1 Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0

我知道问题在于 URL 中的查询结构不正确,我想在发生这种情况时创建警报。

【问题讨论】:

  • 能否也提供response的值?
  • 你能控制台JSON.parse(response)吗?
  • @SookieSingh no 我收到类似的错误qgis2web.js:432 Uncaught (in promise) SyntaxError: Unexpected token o in JSON at position 1,因为它无法解析响应。
  • 表示已经解析过了。你不必解析。

标签: javascript error-handling fetch


【解决方案1】:

您得到的结果已经是 JSON。你可以这样使用它:

fetch(url2, {
    method: 'POST',
    signal: signal,
}).then(function(response) {
    var features = new ol.format.GeoJSON().readFeatures(response);
});

【讨论】:

  • 哦,谢谢,我现在明白了,这很有帮助,让我更容易尝试解决错误,该错误现在位于 var features 行
  • 很高兴为您提供帮助! :)
  • 实际上这会导致我在进行此更改时知道正确的查询出现问题,将尝试找出原因
  • 好吧,您可以为此添加额外的检查。首先检查它是否是JSON并采取相应措施。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-09-17
  • 2019-06-16
  • 1970-01-01
  • 1970-01-01
  • 2019-01-18
  • 1970-01-01
  • 2018-05-20
相关资源
最近更新 更多