This post was most recently updated on March 15th, 2016
HandleError Attribute
1 2 3 4 |
</system.web> ... <customErrors mode="On" defaultRedirect="Error.htm"/> </system.web> |
HandleError Attribute at Action Method Level
1 2 3 4 5 6 |
[HandleError(ExceptionType = typeof(System.Data.DataException), View = "DatabaseError")] public ActionResult Index(int id) { var db = new MyDataContext(); return View("Index", db.Categories.Single(x => x.Id == id)); } |
HandleError Attribute at Controller Level
1 2 3 4 5 |
[HandleError(ExceptionType = typeof(System.Data.DataException), View = "DatabaseError")] public class HomeController : Controller { /* Controller Actions with HandleError applied to them */ } |
HandleError Attribute at Global Level
1 2 3 4 5 6 7 8 9 10 |
public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new HandleErrorAttribute { ExceptionType = typeof(System.Data.DataException), View = "DatabaseError" }); filters.Add(new HandleErrorAttribute()); //by default added } |
Extending HandleError Filter for logging and handling more errors
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
public class CustomHandleErrorAttribute : HandleErrorAttribute { public override void OnException(ExceptionContext filterContext) { if (filterContext.ExceptionHandled || !filterContext.HttpContext.IsCustomErrorEnabled) { return; } if (new HttpException(null, filterContext.Exception).GetHttpCode() != 500) { return; } if (!ExceptionType.IsInstanceOfType(filterContext.Exception)) { return; } // if the request is AJAX return JSON else view. if (filterContext.HttpContext.Request.Headers["X-Requested-With"] == "XMLHttpRequest") { filterContext.Result = new JsonResult { JsonRequestBehavior = JsonRequestBehavior.AllowGet, Data = new { error = true, message = filterContext.Exception.Message } }; } else { var controllerName = (string)filterContext.RouteData.Values["controller"]; var actionName = (string)filterContext.RouteData.Values["action"]; var model = new HandleErrorInfo(filterContext.Exception, controllerName, actionName); filterContext.Result = new ViewResult { ViewName = View, MasterName = Master, ViewData = new ViewDataDictionary(model), TempData = filterContext.Controller.TempData }; } // log the error by using your own method LogError(filterContext.Exception.Message, filterContext.Exception); filterContext.ExceptionHandled = true; filterContext.HttpContext.Response.Clear(); filterContext.HttpContext.Response.StatusCode = 500; filterContext.HttpContext.Response.TrySkipIisCustomErrors = true; } } |