This filter is triggered when an exception occurs on the system and can be handled by the thrown exception. All Exceptionfilter filters are implemented from the Iexceptionfilter interface
Public Interface Iexceptionfilter { void onexception (Exceptioncontext filtercontext); }
Implement the Onexception method to implement custom handling of exceptions
MVC4 implementation of the default exception handling mechanism, the source code is as follows
Public Virtual voidonexception (Exceptioncontext filtercontext) {if(Filtercontext = =NULL) { Throw NewArgumentNullException ("Filtercontext"); } if(filtercontext.ischildaction) {return; } //If Custom Errors is disabled, we need to let the normal ASP. Exception Handler//Execute so, the user can see useful debugging information. if(filtercontext.exceptionhandled | |!filterContext.HttpContext.IsCustomErrorEnabled) {return; } Exception Exception=filtercontext.exception; //If this is not an HTTP $ (for example, if somebody throws an HTTP 404 from an action method),//ignore it. if(NewHttpException (NULL, exception). Gethttpcode ()! = -) { return; } if(!Exceptiontype.isinstanceoftype (Exception)) { return; } stringControllername = (string) filtercontext.routedata.values["Controller"]; stringActionName = (string) filtercontext.routedata.values["Action"]; Handleerrorinfo Model=NewHandleerrorinfo (filtercontext.exception, Controllername, ActionName); Filtercontext.result=NewViewResult {ViewName=View, Mastername=Master, ViewData=NewViewdatadictionary(model), TempData=FilterContext.Controller.TempData}; Filtercontext.exceptionhandled=true; FilterContext.HttpContext.Response.Clear (); FilterContext.HttpContext.Response.StatusCode= -; //Certain versions of IIS would sometimes use their own error page when//they detect a server error. Setting This property indicates that we//want it to a try to render ASP. NET MVC ' s error page instead.FilterContext.HttpContext.Response.TrySkipIisCustomErrors =true; }
Application_Start add Handleerrorattribute to the global filter globalfiltercollection, the system handles the exception.
public class Myexceptionhandleattribute:handleerrorattribute { public Myexceptionhandleattribute (): base () {} public void Span style= "color: #000000;" > Onexception (Exceptioncontext filtercontext) { base . Onexception (Filtercontext); // logging
Add Myexceptionhandleattribute in globalfiltercollection to use a custom exception filter to handle
MVC Four Filter-exceptionfilter