Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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; }); 
like image 316
prostock Avatar asked Dec 17 '10 01:12

prostock


People also ask

How do I catch a JSON parse error?

The best way to catch invalid JSON parsing errors is to put the calls to JSON. parse() to a try/catch block.

Do you need to try catch JSON parse ()?

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...

Does JSON parse throw an error?

JSON. parse() parses a string as JSON. This string has to be valid JSON and will throw this error if incorrect syntax was encountered.

What is JSON parser exception?

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.


2 Answers

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)!     } } 
like image 125
UltraInstinct Avatar answered Sep 22 '22 10:09

UltraInstinct


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
like image 25
Sky Voyager Avatar answered Sep 18 '22 10:09

Sky Voyager