March 18th 2010

Handling Errors During Ajax Calls With ASP.NET MVC

Gracefully handling errors that occur during Ajax calls in a simple yet standard way that didn’t clutter up my methods with a lot of extra code took a while to figure out.

I ended up creating an OnException action filter that I place on my controller or methods as appropriate. When an error is thrown in a method or controller that is decorated with the attribute, execution goes to the filter. Generally I try and throw custom exceptions with an appropriate message. If the request was made via Ajax, the code in the filter below creates a JsonResult with a message to be sent back to the client.

On the client side, I then have a jQuery $.ajaxSetup method that sets how all jQuery Ajax calls handle their errors.

This seems to have worked out pretty well for me. Would you do anything different?