How to capture your client-side errors using Elmah

For those of you who have never heard of Elmah before (where have you been!) it is a powerful and simple way to log errors on your website – go use it, you’ll love it! What I hadn’t considered before was that it could also log client side javascript errors . I picked up this tip from @craigshoemaker on his plurasight course called HTML5 Line of Business Apps with Bootstrap, MVC4 and Web API.

The basic idea is to hook into the ‘window.onerror’ javascript event and to call a dedicated server side endpoint who’s responsible for logging the event in elmah.

Create the endpoint to receive the errors

In his course Craig sets this up with a web API end point but I’m going to use a MVC controller action method. The code here has 3 main parts:

  1. The ErrorInputModel
  2. The client side exception
  3. The end point to post the exception too.

To use this method you would simple post data that conforms the the ErrorInputModel to the address <site path>/error/record.

Hook onto the onError event and post it to the endpoint you set up above

Again I have adapted craigs version as he chooses to use plain javascript where as i have opted to use jQuery ajax.

As you can see it simply builds up the error input model and posts it to the mvc action method.

I hope you find that useful.

About the Author Daniel

I'm a professional software engineer of near on 15 years. Lucky enough to work for a small but rapidly growing company in London called Redington. They have given me the technical freedom to learn some cutting edge technologies like CQRS and Event Sourcing. Now I'm sharing what I learn here.

follow me on: