JQuery JSON parsing error handling

ok I have the following code that parses JSON from ajax response using $ .parseJSON jquery

try{ var indata = $.parseJSON(rsp); }catch(err){ alert("an error occured"); } 

Now that I want to hide all possible errors, I tried to do some error handling, which usually try and catch now this code does not work. I intentionally make invalid JSON and pass it to $.parseJSON , but it really doesn't work. Now my question is how can I handle this error gracefully

+4
source share
3 answers

I would recommend handling errors in jQuery jQuery callback. If you specify dataType as json, you should enter the error callback instead of success if the json string is incorrectly formatted

+7
source

The code is fine, it should work if you don't try "jQuery" instead of "$". eg

 try{ var indata = jQuery.parseJSON(rsp); }catch(err){ alert("an error occured"); } 
+1
source

From the jQuery API documentation :

Prior to jQuery 1.9, $ .parseJSON returned null instead of throwing an error if it was given an empty string, null or undefined, although they are not valid JSON.

Are you using jQuery version older than 1.9?

0
source

Source: https://habr.com/ru/post/1416535/


All Articles