title: Handling Exceptions in MVC JSON Controller Action
body: <p>I'm looking for the best approach at handling errors in a controller when returning a JSON result. </p>
  
  <p>Firstly, what would be the best practice if I get an unhandled exception in my controller and I'm returning JSON? I'm thinking 400 or 500 error? Client checks the status and does whatever.</p>
  
  <p>I'm playing with a FilterAttribute and an IExceptionFilter but I can't get the OnException function to call. I've got the attribute applied to a controller action.</p>
  
  <p>Any ideas why that might not be calling?</p>
  
  <pre><code>[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = false, AllowMultiple = false)]
  public sealed class AjaxHandleErrorAttribute : FilterAttribute, IExceptionFilter
  {
      // This is never called !!!
      public void OnException(ExceptionContext filterContext)
      {
          if (filterContext == null)
          {
              throw new ArgumentNullException("filterContext");
          }
  
          if (filterContext.Exception != null 
              &amp;&amp; !filterContext.ExceptionHandled)
          {
              ...
              filterContext.HttpContext.Response.StatusCode = 400;
              filterContext.HttpContext.Response.StatusDescription = "Error processing                 request";
              ...
          }
      }
  }
  
  public class MyController : Controller
  {
      public MyController(IMyRepository repo)
      {
          ...
      }
  
      [AjaxHandleError]
      public ActionResult GetSomeJson(int anId)
      {
          throw new System.Exception();
      }
  }
  </code></pre>