简体   繁体   中英

how to catch the error in fetch response conversion to json and do something?

I am using this fetch request, and there are times when the response is ok (200) but the response can't be converted to json. I'm unsure of how to catch this error, i have tried using try/catch but can't figure out exactly where those clauses should be placed. I am not a javascript expert, any advice would be appreciated!

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

this is the response I get and the error:

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

I know the problem is that the query in the URL is not structured properly and I want to create an alert when this happens.

The result you are getting is already JSON. You can use it like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM