ebi
ebi

Reputation: 4902

Is there a way to globally catch JSON parse errors?

Either in plain JS or with jQuery is good. I'm already using the $(window).error function, but it only gives the error message "Unexpected token u" on line 1, not any useful line numbers or variable names or what it was trying to parse.

Edit: This is in a Chrome extension.

Upvotes: 0

Views: 204

Answers (1)

Joseph
Joseph

Reputation: 119827

You could create a script that patches up the methods found in the JSON namespace, and do some custom error trapping there.

Something like this should do. If you use custom a custom JSON library, then place this after it.

//sample patch for parse
(function(){

  //store the original parse
  var parse = JSON.parse;

  //patched parse function
  JSON.parse = function(){
    try{
      //try parsing
      return parse.apply(this,arguments);
    } catch(e){
      //something went wrong
      //custom code here
      throw e;
    }
  }

}());

Upvotes: 4

Related Questions