In the event of an exception, we do not want to let the customer see the reason for the wrong language, often make a 404 error page, will all occurrences of the exception jumps to the page, and the exception information written in the log. The steps are as follows:
1, let us see Global.asax page Application_Start () method has filterconfig.registerglobalfilters (globalfilters.filters);
protected void Application_Start () { arearegistration.registerallareas (); Webapiconfig.register (globalconfiguration.configuration); Filterconfig.registerglobalfilters (globalfilters.filters); Routeconfig.registerroutes (routetable.routes); Bundleconfig.registerbundles (bundletable.bundles); Authconfig.registerauth ();}
2, F12, go in the method, register for our custom exception handler
Public Static void registerglobalfilters (globalfiltercollection filters) { filters. ADD (new// custom filter }
3. Adding class files Myexceptionattribute began to write our custom classes, notice that we are going to inherit our MVC exception handler class Handleerrorattribute, in which we define a queue that is used to
Storing the exception information. And at the appropriate time to write these exception information to the log, where to write it, please look down.
Public classMyexceptionattribute:handleerrorattribute {/// <summary> ///capturing exceptions in the Controller method/// </summary> /// <param name= "Filtercontext" ></param> Public Override voidonexception (Exceptioncontext filtercontext) {exceptionqueue.enqueue (filtercontext.exception); FilterContext.HttpContext.Response.Redirect ("/error.html"); //base. Onexception (filtercontext); } Public StaticQueue<exception> Exceptionqueue =NewQueue<exception>(); }
4. We also open a thread in Application_Start () to write the information in the queue to the log
System.Threading.ThreadPool.QueueUserWorkItem (A = { while(true) { if(MyExceptionAttribute.exceptionQueue.Count () >0) {Exception ex=MyExceptionAttribute.exceptionQueue.Dequeue (); if(Ex! =NULL) {logservice.erroroperationstring (ex. ToString ()); } Else{System.Threading.Thread.Sleep (9000); } } Else{System.Threading.Thread.Sleep (9000); } } });
At this point a complete MVC exception handling is done ...
MVC Unified Exception Handling