What is the best strategy to handle unhandled Exceptions (error 500 responses) in Asp.Net MVC actions for Ajax requests? What is the best strategy to handle unhandled Exceptions (error 500 responses) in Asp.Net MVC actions for Ajax requests? json json

What is the best strategy to handle unhandled Exceptions (error 500 responses) in Asp.Net MVC actions for Ajax requests?


Here's how I solved this problem:

public class HandleJsonError : HandleErrorAttribute{    public override void OnException(ExceptionContext exceptionContext)    {        if (!exceptionContext.HttpContext.Request.IsAjaxRequest() || exceptionContext.Exception == null) return;        exceptionContext.HttpContext.Response.StatusCode = (int) HttpStatusCode.InternalServerError;        exceptionContext.Result = new JsonResult                                   {                                       Data = new                                                  {                                                      exceptionContext.Exception.Message,                                                      exceptionContext.Exception.StackTrace                                                  }                                   };        exceptionContext.ExceptionHandled = true;    }}


You could override OnException in the controller and put in some logic to return a JSON error response which you would need to handle in your javascript calling code:

protected override void OnException(ExceptionContext filterContext)    {        if (filterContext.HttpContext.Request.IsAjaxRequest())        {            filterContext.Result = Json("...");        }        else        {            base.OnException(filterContext);        }    }

If you want to do it 'properly', you can write an actionfilter with pretty much the same code and apply it to all controllers. If you are using MVC3, you can make it a global filter so it will apply to all controllers.


You can use a custom ActionFilter and then inside of that if it was a javascript request you can then format the response as a JSON object instead of an HTML page. HandleError would be a good place to look at extending your base class from.

An alternative option if you didn't want to do an actio filter would be to override OnException in your controller and set exceptionContext.Result to a new JsonResult that indicates failure.