Logging client side Javascript errors - quickly

Mar 12, 2017 12:03

I've been building applications for serveral clients, and myself over the course of the last couple of years in Cordova. I find Cordova great for getting apps built using technologies I already know well (HTML, CSS, JS) but recently I have hit a problem where I have an application with a lot of users (10k+ active users) and some are reporting errors.

I needed a quick way of reporting these errors - so I wrote a few lines of JS to collect them!

Firstly, we need an event to listen to for when there is an error. Luckily, there is one we can use - window.onerror. Looking at that link, we know we can write this:

window.onerror = function(message, file, line, col, err) {
  //-- We have an error - lets send it off
  sendError(file + ":" + line + " => " + message);

Our sendError function is super simple - we make an AJAX request with jQuery (as its already provided to us) to our server.

function sendError(info)
    url: window.apiURL + "error/log",
    contentType: 'application/json; charset=utf-8'
    type: 'POST',
    data: JSON.stringify({ error: info, device: window.userDevice }),

Its not super pretty, but it works. On my applictions API backend, I have a method which takes this error in, and pushes it to my dashboard and stores any errors so I can check out any issues. For such a small bit of code, it works really well.

I'm currently looking into Sentry for a sturdy solution going forwards - but I'd love to hear your stories about how you collate and act on client side issues!