Proper way to catch exception from JSON.parse

JavascriptXmlhttprequest

Javascript Problem Overview


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

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

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 :

Solution 3 - Javascript

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.

Solution 4 - Javascript

if you are looking for a generalized function for this, give this a shot.

const parseJSON = (inputString, fallback) => {
  if (inputString) {
    try {
      return JSON.parse(inputString);
    } catch (e) {
      return fallback;
    }
  }
};

Solution 5 - Javascript

I recommend you to use this one as a ES6 best practice. Using Error object

try {
  myResponse = JSON.parse(response);
} catch (e) {
  throw new Error('Error occured: ', e);
 }

Above answer also helpful,

Solution 6 - Javascript

You can try this:

Promise.resolve(JSON.parse(response)).then(json => {
    response = json ;
}).catch(err => {
    response = response
});

Solution 7 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionprostockView Question on Stackoverflow
Solution 1 - JavascriptUltraInstinctView Answer on Stackoverflow
Solution 2 - JavascriptSky VoyagerView Answer on Stackoverflow
Solution 3 - JavascriptubuntugodView Answer on Stackoverflow
Solution 4 - JavascriptKartik MalikView Answer on Stackoverflow
Solution 5 - JavascriptBushra MustofaView Answer on Stackoverflow
Solution 6 - Javascriptvivek javaView Answer on Stackoverflow
Solution 7 - JavascriptJason ClayView Answer on Stackoverflow