I’m using JSON.parse
on a response that sometimes contains a 404 response. In the cases where it returns 404, is there a way to catch an exception and then execute some other code?
data = JSON.parse(response, function (key, value) { var type; if (value && typeof value === 'object') { type = value.type; if (typeof type === 'string' && typeof window[type] === 'function') { return new(window[type])(value); } } return value; });
The best way to catch invalid JSON parsing errors is to put the calls to JSON. parse() to a try/catch block.
parse encounters invalid JSON in a string, it'll throw an error. JSON. stringify throws errors when it tries to convert a circular structure to JSON. Therefore, we should use try...
JSON. parse() parses a string as JSON. This string has to be valid JSON and will throw this error if incorrect syntax was encountered.
When it detects invalid JSON, it throws a JSON Parse error. For example, one of the most common typos or syntax errors in JSON is adding an extra comma separator at the end of an array or object value set.
i post something into an iframe then read back the contents of the iframe with json parse...so sometimes it's not a json string
Try this:
if(response) { try { a = JSON.parse(response); } catch(e) { alert(e); // error in the above string (in this case, yes)! } }
We can check error & 404 statusCode, and use try {} catch (err) {}
.
You can try this :
const req = new XMLHttpRequest(); req.onreadystatechange = function() { if (req.status == 404) { console.log("404"); return false; } if (!(req.readyState == 4 && req.status == 200)) return false; const json = (function(raw) { try { return JSON.parse(raw); } catch (err) { return false; } })(req.responseText); if (!json) return false; document.body.innerHTML = "Your city : " + json.city + "<br>Your isp : " + json.org; }; req.open("GET", "https://ipapi.co/json/", true); req.send();
Read more :
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With