ASP.NET MVC 5 error handling

The best way is using Global.Asax, because you can manage all types of errors (Ajax calls/ all of unexpected Errors). with others you can’t do it.

Like this:

protected void Application_Error()
{
    HttpContext httpContext = HttpContext.Current;
    if (httpContext != null)
    {
        RequestContext requestContext = ((MvcHandler)httpContext.CurrentHandler).RequestContext;
        /* When the request is ajax the system can automatically handle a mistake with a JSON response. 
           Then overwrites the default response */
        if (requestContext.HttpContext.Request.IsAjaxRequest())
        {
            httpContext.Response.Clear();
            string controllerName = requestContext.RouteData.GetRequiredString("controller");
            IControllerFactory factory = ControllerBuilder.Current.GetControllerFactory();
            IController controller = factory.CreateController(requestContext, controllerName);
            ControllerContext controllerContext = new ControllerContext(requestContext, (ControllerBase)controller);

            JsonResult jsonResult = new JsonResult
            {
                Data = new { success = false, serverError = "500" },
                JsonRequestBehavior = JsonRequestBehavior.AllowGet
            };
            jsonResult.ExecuteResult(controllerContext);
            httpContext.Response.End();
        }
        else
        {
            httpContext.Response.Redirect("~/Error");
        }
    }
}

Leave a Comment