JavaScript, Web

Logging JavaScript exceptions. Custom solution + ELMAH

Development team was reported about critical bug in production. First thing they did was checking server logs but they were empty. Impossible! On the other hand the client sent screenshot with error alert.
Have you ever experienced such scenario? It happened to me many times. And it’s nothing extraordinary – the more code on the client, the more probable to commit a bug. The worst thing is that’s so hard to track such bugs. After all it came out that’s not that hard. Here’s my solution:

  1. (Optional but recommended: use ELMAH. It adds a nice error log and page to browse already caught errors + some extra information about context of such errors)
        Install-package elmah
    or if using ASP.NET MVC
        Install-package elmah.mvc
  2. Listen for client-side errors and send them to the server (custom errorLogging.js script):
    jserror3
    Please note, that the code above does not work on IE7 and below (just to keep it simple). IE supports JavaScript stacktrace from version 10+ that’s why there is “if” clause between lines 16-18.
  3. Add back-end code to listen for exception logsjserror4
    You could use MVC or WebAPI controller, but handlers feels more like infrastructure. If you don’t want to use ELMAH, then replace line 36 with your logging mechanism (or “throw jsException“).
  4. Create exception type specific to JavaScriptjserror5
    It’s particularly important to override ToString() method as it’s used by ELMAH to dump exception details.
  5. Connect it all together: add script reference to errorLogging.js and register JavaScriptErrorHandler class in global.asax.cs

And there it is! If you don’t want to do it yourself go to my github page and download a working sample: Blog.ClientSideExceptionCatching

After playing for some time here are the results. As you can see both server-side and client-side errors are kept together with the time they occurred.
jsError
If you go deeper then you see exception details (message, stacktrace).

jsError2_1

jsError2_2

This is something that we get by our hands. Elmah also gives us a very useful gift as it logs all server variables, including HTTP_USER_AGENT that tells us what browser was used on the client. You don’t need to ask the user for such things. Handy!

Off-topic/final points

  • First I tried jsnlog but failed. It forced me to use Common.Logging and was not working out-of-the-box.
  • Beware of Internet Explorer – it generates localized exception messages (see the first elmah screenshot) and may not support stack trace
Advertisements