The handling of exception information is very important in the program, providing exception property interceptors to handle exception information in ASP. Exception interceptors have nothing to do, just write a class, Inherit another class (System.Web.Mvc.FilterAttribute) and an interface (System.Web.Mvc.IExceptionFilter), implement the interface inside the Onexception method.
code example:
Exception Interceptor Class:
1 usingSystem;2 usingSystem.Collections.Generic;3 usingSystem.Linq;4 usingsystem.web;5 6 namespaceAttributedemo.common7 {8 /// <summary>9 ///Exception Information InterceptorTen /// </summary> One Public classExceptionFillterAttribute:System.Web.Mvc.FilterAttribute, System.Web.Mvc.IExceptionFilter A { - #regionThis method is executed when the requested action exception occurs - /// <summary> the ///This method is executed when the requested action exception occurs - /// </summary> - /// <param name= "Filtercontext" ></param> - voidSystem.Web.Mvc.IExceptionFilter.OnException (System.Web.Mvc.ExceptionContext filtercontext) + { - //Here you can record what you're going to do when something happens, proportional write log + stringMessage =FilterContext.Exception.Message; Afiltercontext.controller.viewdata["errormessage"] =message; at - //returns the result to the client -Filtercontext.result =NewSystem.Web.Mvc.ContentResult () - { -Content ="the error:)", -ContentEncoding =System.Text.Encoding.UTF8 in }; - to +filtercontext.exceptionhandled =true;//tell the system that the exception has been handled and no more processing - the //filtercontext.exceptionhandled = false; //tell the system that this exception is not handled and needs to be processed * } $ #endregionPanax Notoginseng - the } +}
Controller class:
1 usingSystem;2 usingSystem.Collections.Generic;3 usingSystem.Linq;4 usingsystem.web;5 usingSYSTEM.WEB.MVC;6 7 namespaceattributedemo.controllers8 {9 /// <summary>Ten ///Test exception Blocker One /// </summary> A[AttributeDemo.Common.ExceptionFillter]//This exception intercept attribute is written here to indicate that all action exceptions to the controller are intercepted . - Public classExceptionfilltertestcontroller:controller - { the // - //GET:/exceptionfillter/ - - /// <summary> + ///test for exception blocking - /// </summary> + /// <returns></returns> A //[AttributeDemo.Common.ExceptionFillter]//This exception intercept attribute is written here to intercept only the exception information for the action. at Publicactionresult testexceptionfillter () - { - inti =int. Parse ("SD");//This is intentionally throwing an exception for testing . - returnView (); - } - in Publicactionresult Index () - { to returnView (); + } - the } *}
When the action name is called Testexceptionfillter, the action method throws an exception and executes the Onexception method inside the exception intercept class to handle the results, see:
ASP. NET MVC Exception Exception Interceptor Fillter