Proper way to catch exception from JSON.parse

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

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 :

  • Catch a 404 error for XHR

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.