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 exec
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 :
I am fairly new to Javascript. But this is what I understood:
JSON.parse()
returns SyntaxError
exceptions when invalid JSON is provided as its first parameter. So. It would be better to catch that exception as such like as follows:
try {
let sData = `
{
"id": "1",
"name": "UbuntuGod",
}
`;
console.log(JSON.parse(sData));
} catch (objError) {
if (objError instanceof SyntaxError) {
console.error(objError.name);
} else {
console.error(objError.message);
}
}
The reason why I made the words "first parameter" bold is that JSON.parse()
takes a reviver function as its second parameter.
You can try this:
Promise.resolve(JSON.parse(response)).then(json => {
response = json ;
}).catch(err => {
response = response
});
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)!
}
}
This promise will not resolve if the argument of JSON.parse() can not be parsed into a JSON object.
Promise.resolve(JSON.parse('{"key":"value"}')).then(json => {
console.log(json);
}).catch(err => {
console.log(err);
});