Logging Client Side Javascript Errors

This seems to be something a lot of people don't know how to do so here's a quick intro. You might have a great error logging setup on the backend of your site but most people have no idea what's going on with the frontend. As an example, wouldn't it be great to be able to see what browser version that one user who always gets JS errors was actually using, or even track the user's id so you can reference their profile data to get in contact with them.

That's where logging client side javascript errors comes in handy. You'll need to add logging code on the frontend and a simple API on the backend. And as a disclaimer, this code is not 100% vetted, it's just a quick example to get you started.

Frontend

Example logging of javascript errors using jQuery

try {
  window.onerror = function(err, url, line) {
    //api url
    var apiUrl = 'your/api/url';

    //suppress browser error messages
    var suppressErrors = true;

    $.ajax({
      url: apiUrl,
      type: 'POST',
      data: {
        errorMsg: err,
        errorLine: line,
        queryString: document.location.search,
        url: document.location.pathname,
        referrer: document.referrer,
        userAgent: navigator.userAgent
      }
    });

    return suppressErrors;
  };
} catch(e) { }



Backend

Example route to log the error in Laravel

Route::post('your/api/url', function()
{
    Log::error('Javascript error:' . json_encode(Input::get()));
});



Log File

This gives you the following information in your log file

2012-04-17 23:40:44 ERROR - Javascript error:{"errorMsg":"Uncaught ReferenceError: notDefined is not defined","errorLine":"119","queryString":"","url":"\/Personal\/laravel\/public\/","referrer":"http:\/\/localhost\/Personal\/laravel\/"}




April 17 2012