Search code examples
javascriptxmlhttprequest

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

Solution

  • 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) {
        let a;
        try {
            a = JSON.parse(response);
        } catch (e) {
            return console.error(e); // error in the above string (in this case, yes)!
        }
        // if no error, we can now keep using "a"
    }