title: In ASP.NET MVC how to refactor try/catch and return JSON error message?
body: <p>How best to create a base controller in a new ASP.NET MVC application that will contain boilerplate code to handle all try/catch routines for every action in derived controllers and return a standard JSON error message after logging to Nlog. I would also like to handle 404 errors to redirect to a custom 404 view. I aim using OWIN cookie authentication and would like to signout when the cookie expires. All my actions will be returning JsonResult and invoked via jQuery Ajax. </p>
  
  <p>In previous projects I've used the following approach:</p>
  
  <p>In <code>Global.asax.cs</code></p>
  
  <pre><code>  protected void Application_Error(object sender, EventArgs e)
      {
          Exception lastError = Server.GetLastError();
          Server.ClearError();
  
          var statusCode = 0;
  
          statusCode = lastError.GetType() == typeof(HttpException) ? ((HttpException)lastError).GetHttpCode() : 500;
  
          var routeData = new RouteData();
          routeData.Values.Add("controller", "Error");
          routeData.Values.Add("statusCode", statusCode);
          routeData.Values.Add("exception", lastError);
  
          if (new HttpRequestWrapper(HttpContext.Current.Request).IsAjaxRequest())
          {
              routeData.Values.Add("action", "Ajax");     
          }
          else
          {
              routeData.Values.Add("action", "Index");
          }
  
          var requestContext = new RequestContext(new HttpContextWrapper(Context), routeData);
  
          IController controller = new ErrorController();
          controller.Execute(requestContext);
  
          Response.End();
      }
  </code></pre>
  
  <p>In <code>ErrorController.cs</code></p>
  
  <pre><code> public class ErrorController : Controller
  {
      public ActionResult Index(int statusCode, Exception exception)
      {
          var model = new ErrorModel { HttpStatusCode = statusCode, Exception = exception.Message };
  
          Response.StatusCode = statusCode;
  
          return View(model);
      }
  
      public JsonResult Ajax(int statusCode, Exception exception, Dictionary&lt;string,string&gt; validationErrors = null)
      {
          var model = new ErrorModel { HttpStatusCode = statusCode, Exception = exception.Message };
  
          if (exception.GetType() == typeof (DbEntityValidationException))
          {
              model.ValidationErrors = null;
          }
          else
          {
              model.ValidationErrors = validationErrors;
          }
  
          Response.StatusCode = statusCode;
  
          return Json(model, JsonRequestBehavior.AllowGet);
      }
  }
  </code></pre>