Handling Errors During Ajax Calls With ASP.NET MVC

by Bill Beckelman 18. March 2010 12:54

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.

 

Code Snippet
  1. using System;
  2. using System.Net;
  3. using System.Web.Mvc;
  4.  
  5. namespace Website.ActionFilters
  6. {
  7.     [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)]
  8.     public class AjaxException : ActionFilterAttribute, IExceptionFilter
  9.     {
  10.         public void OnException(ExceptionContext filterContext)
  11.         {
  12.             if (!filterContext.HttpContext.Request.IsAjaxRequest()) return;        
  13.     
  14.             filterContext.Result = AjaxError(filterContext.Exception.Message, filterContext);                
  15.  
  16.             //Let the system know that the exception has been handled
  17.             filterContext.ExceptionHandled = true;
  18.         }
  19.         
  20.         protected JsonResult AjaxError(string message, ExceptionContext filterContext)
  21.         {
  22.             //If message is null or empty, then fill with generic message
  23.             if (String.IsNullOrEmpty(message))
  24.                 message = "Something went wrong while processing your request. Please refresh the page and try again.";
  25.  
  26.             //Set the response status code to 500
  27.             filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
  28.  
  29.             //Needed for IIS7.0
  30.             filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
  31.  
  32.             return new JsonResult
  33.             {
  34.                 Data = new{ ErrorMessage = message },
  35.                 ContentEncoding = System.Text.Encoding.UTF8,
  36.                 JsonRequestBehavior = JsonRequestBehavior.DenyGet
  37.             };
  38.         }
  39.     }
  40. }

 

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

Code Snippet
  1. //Set defaults for all of the ajax calls
  2. $.ajaxSetup({
  3.     type: "POST",
  4.     cache: false,
  5.     error: function(request) {
  6.         //code to display message to user
  7.     }
  8. });

 

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

Tags:

ASP.NET MVC

Comments


About Me

I live and work in Salt Lake City, Utah. My background is in aviation. I have a degree in Aeronautical Science from Embry-Riddle Aeronautical University in Prescott, AZ. I have worked as a commercial airline pilot and most recently as a technical advisor for a charter airline.