Javascript error reporting for fun and profit
Sunday, February 12, 2012 at 03:56PM Here at PipelineDeals, our app is very Javascript intensive. In fact, for our Jupiter release, we moved much of our logic from rails to the browser and Javascript, using Backbone.js, Coffeescript and a host of other new cutting edge technologies.
During deploys and other edge cases, we want to know if a user has received a javascript error, just like we would with any other type of exception. We deploy very frequently. A few weeks ago we ran into a problem where one of our app servers did not minify and concatenate one of our javascript files correctly, and led to a host of issues that customers saw. In order to prevent this in the future, we decided to search around and see if we could have javascript errors report to one of our favorite tools, NewRelic RPM.
As it turns out, catching and reporting Javascript errors is pretty easy. We ended up hooking into window.onerror, which we define right after we add jQuery, right at the top of the page.
// Determine if the error occurred before or after document ready
jQuery(function() { window.documentIsReady = true; });
// report a maximum of 5 errors
window.MaximumErrorCount = 5;
window.onerror = function(errorMsg, file, lineNumber) {
window.errorCount || (window.errorCount = 0);
// this example assumes a ppd object that has various information about
// our environment and our logged in user.
if (ppd.env == 'production' && window.errorCount <= window.MaximumErrorCount) {
window.errorCount += 1;
// post the error with all the information we need.
jQuery.post('/javascript_error', {error: errorMsg, file: file, location: window.location.href, lineNumber: lineNumber, userId: ppd.User.id, documentReady: window.documentIsReady, ua: navigator.userAgent});
}
}
The above code will execute if the user receives a javascript error. It will then do an ajax post to our app, which will handle the error.
class JavascriptErrorController < ApplicationController
def javascript_error
# post the error to newrelic.
# You could also send an email, notify hipchat, whatever.
NewRelic::Agent.notice_error("Javascript error: #{params[:error]}", {:uri => params[:location], :params => params})
end
head :ok
end
end
Not only has this been invaluable for catching that rare, but painful asset problem, but it will also catch legitimate issues and race cases where sometimes a variable might not be defined.
In NewRelic, javascript errors get report just like any other error, and if we do have an asset problem, our error rate will shoot through the roof and all the devs will be notified.


