Writing good software is hard, and often things go wrong in unexpected ways when software is deployed to live. A mantra that I’ve been trying to live by is to “never rely on your users/clients/customers reporting problems”, if anything this should be the absolute last thing to rely on.
I’ve previously talked about how I have been deploying metrics and fault reporting code for all my clients, regardless of what software they’re running, and how I’ve built support for these into Known core.
These reports produce a detailed insight into the code as it runs under real usage, as well as a detailed bug log should something fail. The fault reporting messages in particular have possibly been one of the most useful things I’ve ever done, and have already been responsible for discovering a number of rare failure modes on software that had thus far neither shown up in testing or had been reported.
Today I had a particularly thorny Javascript issue to debug, and it got me thinking about how I could capture javascript errors from client browsers, have errors logged in a central way, and even get metric and fault reporting as I currently do with PHP errors.
Turns out it’s actually quite easy, and in a nutshell you need to:
- Write an endpoint which will log your error message in the appropriate way, sending a fault report as necessary
- Write a bit of javascript code to call this endpoint, and listen to an error event, e.g.
window.addEventListener('error', function (error) { var stack = error.error.stack; var message = error.error.toString(); if (stack) message += '\n' + stack; ... call your ajax endpoint... });
The latest build of Known now has support for this: now, Javascript messages will get logged in your normal logs, metrics counted, and if you’ve enabled oops reporting, you’ll get an email when a client triggers a Javascript error.
Hopefully you’ll find this as useful as I have!