Better way of using parseJSON

While doing on some project I found myself in situation where, when parsing JSON data,  if server thrown an error (syntax error for example), I finished with only parsing error. Without information what happened wrong (without data that server returned), I was unable to solve the problem. So I decided to create function parseJSON2. Not to much creative name, but it did the job. Here it is:

jQuery._parseJSON2 = function(data) {
	var parsed = null;
	try {
		parsed = $.parseJSON(data);
	} catch(err) {
		console.error(err);
		console.error(data);
	}
	return parsed;
}

I modified my code to use this function instead of regular parseJSON function. This way, when server returned error, I had it printed in my console.

So feel free to use this function if you find it useful.

Edit:

Now here is another idea: When some error happen at the client side, send it to server.

During testing period, you may miss some use cases where error is hidden. But clients will for sure find that little bug.

That way you can track when some errors occurs at client side, which you did not reproduced earlier. And you can solve them.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.