Can Elmah log JavaScript errors? Yes!

When it comes to logging server side exceptions/errors in my ASP.net projects, Elmah is my first choice. It is my favourite because of following features:

  • Simple and straightforward to install in your project
  • Powerful reporting of all unhandled exceptions with stack traces
  • Various storage options to log errors: Microsoft SQL Server, Oracle, SQLite, XML files, In-memory(Default), MySQL, PostgreSQL
  • Receive exceptions on email when they occur

You can read more about elmah and its setup process in an article by Scott Hanselman.
Life would be easy when one tool works for both worlds(client and server). Lets see how can we log JavaScript errors by Elmah sitting at your server.
Elmah expects an object of type derived from Exception class. So, we need to create a custom exception for JS error:
1) Custom exception class for JavaScript errors.

public class JSException : Exception
{
    public string Message { get; set; }
    public string Url { get; set; }
    public int LineNumber { get; set; }
    public string ErrorStack { get; set; }
    public int Column { get; set; }
    public override string ToString()
    {
        return Message + Environment.NewLine +
            "Url: "+Url+Environment.NewLine+
            "Line: " + LineNumber + Environment.NewLine +
            "Column: " + Column + Environment.NewLine +
            (!string.IsNullOrEmpty(ErrorStack) ? ("Stack Trace: "+ErrorStack+Environment.NewLine) : string.Empty) + base.ToString();
    }
}

2) Controller (I am using ASP.net MVC)

public class ErrorController : Controller
{
   public void Index(string message,string url, int line, int column, string stack)
   {
     ErrorSignal.FromCurrentContext().Raise(new JSException
     {
       Message = message,
       Url = url,
       LineNumber = line,
       Column = column,
       ErrorStack = stack
     });
   }
}

3) Client side code snippet to send error to controller. We have to assign a function to window.onerror event at top(under head section) so that it gets attached as soon as the page is ready.

window.onerror = function (message, url, line, column, error) {
            var e = encodeURIComponent;
            (new Image()).src = '@Url.Content("Error")?message=' + e(message) +'&url=' + e(url) +'&line=' + e(line) +(error && error.stack ? '&stack=' + e(error.stack) : '') +(column ? '&column=' + e(column) : '');
        };

We are all set. It’s time to see it in action. Lets generate an error intentionally.
alert(abc); //I have not defined this variable
JS error- abc is undefined
abc is obviously undefined here. Lets see how it is logged in elmah.
See Elmah console
elmah
See the error detail
elmah-detail

If you have liked this article, don’t forget to share it with world.