HandleErrorAttribute
, which, as stated in MSDNRepresents an attribute used to handle an exception that is called by an action method.
HandleErrorAttribute
it is easy to see this. There are the following lines: // If this is not an HTTP 500 (for example, if somebody throws an HTTP 404 from an action method), // ignore it. if (new HttpException(null, exception).GetHttpCode() != 500) { return; }
HandleErrorAttribute
HandleErrorAttribute
does not suit us, well, let's create our own.IExceptionFilter
interface, but we are generally satisfied with the behavior of the standard HandleErrorAttribute
if it handles all exceptions. And since we are almost satisfied with everything, our class will inherit from the HandleErrorAttribute
we don’t HandleErrorAttribute
. public class HandleAllErrorAttribute : HandleErrorAttribute { public override void OnException(ExceptionContext filterContext) { if (filterContext == null) { throw new ArgumentNullException("filterContext"); } // If custom errors are disabled, we need to let the normal ASP.NET exception handler // execute so that the user can see useful debugging information. if (filterContext.ExceptionHandled || !filterContext.HttpContext.IsCustomErrorEnabled) { return; } Exception exception = filterContext.Exception; if (!ExceptionType.IsInstanceOfType(exception)) { return; } string controllerName = (string)filterContext.RouteData.Values["controller"]; string actionName = (string)filterContext.RouteData.Values["action"]; HandleErrorInfo model = new HandleErrorInfo(filterContext.Exception, controllerName, actionName); filterContext.Result = new ViewResult { ViewName = View, MasterName = Master, ViewData = new ViewDataDictionary<HandleErrorInfo>(model), TempData = filterContext.Controller.TempData }; filterContext.ExceptionHandled = true; filterContext.HttpContext.Response.Clear(); filterContext.HttpContext.Response.StatusCode = new HttpException(null, exception).GetHttpCode(); // Certain versions of IIS will sometimes use their own error page when // they detect a server error. Setting this property indicates that we // want it to try to render ASP.NET MVC's error page instead. filterContext.HttpContext.Response.TrySkipIisCustomErrors = true; } }
HandleErrorAttribute
, with the exception of a few lines that check for HttpStatusCode
.customErrors
are customErrors
HandleErrorInfo
ViewResult
, fills it with data and assigns instead of the current filters.Add(new HandleAllErrorAttribute());
View
, let's change the standard ~ / Views / Shared / Error.cshtml : @model System.Web.Mvc.HandleErrorInfo @{ ViewBag.Title = "Error"; } <h2> Sorry, an error occurred while processing your request. </h2> <h3>@Model.Exception.Message</h3>
System.Web
section in the Web.config (which is in the root): <customErrors mode="On" defaultRedirect="Error" />
public ActionResult About() { throw new HttpException(403, " !"); return View(); }
Source: https://habr.com/ru/post/137672/
All Articles