AOP-based MVC blocking exceptions make code more beautiful

Source: Internet
Author: User
Tags httpcontext throw exception

Many years of working with ASP, such as Microsoft's excellent framework today, Microsoft in the MVC-based Thinking framework, also launched its own set of ASP. NET MVC framework, if you personally experienced it, you can not help saying ' beautiful '. Back to, ' pretty ' after all, there is a good idea, which is similar to the idea of AOP, in which the embodiment of the incisively and vividly, today this paper is mainly based on the idea of AOP as an ' anomaly filter '. Our purpose is only one, let Try...catch ... Nowhere to shield, to make the code more robust and graceful.

First, understand how the filter works in MVC

A foreigner's article is such a sketch

By translating the Chinese is like this

There is an exception filter

It is clear from the above table that when the Controller or action executes, the Iexceptionfiter implementation base class will have ' ability ' to handle, where Microsoft implements the implementation class by default in MVC Handleerrorattribute

Look at how this source code is going to work out.

 Public Virtual voidonexception (Exceptioncontext filtercontext) {if(Filtercontext = =NULL)            {                Throw NewArgumentNullException ("Filtercontext"); }            if(!filtercontext.ischildaction && (!filtercontext.exceptionhandled &&filterContext.HttpContext.IsCustomErrorEnabled)) {Exception innerexception=filtercontext.exception; if((NewHttpException (NULL, innerexception). Gethttpcode () = = -) && This. Exceptiontype.isinstanceoftype (innerexception)) {stringControllername = (string) filtercontext.routedata.values["Controller"]; stringActionName = (string) filtercontext.routedata.values["Action"]; Handleerrorinfo Model=NewHandleerrorinfo (filtercontext.exception, Controllername, ActionName); ViewResult result=NewViewResult {ViewName= This. View, Mastername= This. Master, ViewData=NewViewdatadictionary(model), TempData=FilterContext.Controller.TempData}; Filtercontext.result=result; Filtercontext.exceptionhandled=true;                    FilterContext.HttpContext.Response.Clear (); FilterContext.HttpContext.Response.StatusCode= -; FilterContext.HttpContext.Response.TrySkipIisCustomErrors=true; }            }        }

The idea of this code is this

Handleerrorattribute-->handleerrorinfo (model)-->viewresult-->{viewname:error}

That throws an error view in the share folder.

It can be seen in the form of a filter, indicating that it has the ability to ' paste ' in the form of a property controller or action, to make the code more ' beautiful '! Because filter Microsoft also left us the ' filterconfig ' entrance, can be a global ' injection '

At this point, we can see that there are at least two forms to plan my ' anomalies ', one is in the form of attributes ' paste ' on the Controller and Action, and the second is to register with the global ' filterconfig '. No matter what, the result is only one, try...catch ... It's getting away from us, isn't it? Let's keep looking!

Exceptions are thrown out by ' inside ', as we often see in the exception Yellow pages, which are thrown to the outermost of an exception page.

1.action-->handleerrorattribute (default)-->iexceptionfilter-->onexception

2.controller-->handleerrorattribute (default)-->iexceptionfilter-->onexception

Second, customize our exception class


Before customizing our exception helper classes, we first make clear the points:

1. Global exceptions are captured using the Customexceptionattribute custom exception class.

2. The ' Asyncexceptionattribute ' exception is used to capture the ' event ' in JSON format for action Jsonresult.

The order is: Action-->asyncexceptionattribute-->customexceptionattribute-->handleerrorattribute (default)-- Iexceptionfilter-->onexception

An exception occurs in the action, and if it is Jsonresult, it is captured with Asyncexceptionattribute and then the global Customexceptionattribute

When the filtercontext.exceptionhandled=true is set to indicate that this exception ' has been processed ', whereas exceptions are thrown outward in the subsequent capture mechanism, this is freely ordered by their own needs.

1) asyncexceptionattribute definition:

If it is a Jsonresult exception, we do the processing to combine it into a data with a status of success=false,message= ' exception information '.

This does not do filtercontext.exceptionhandled=true processing, in order to let the exception to the ' Out 'customexceptionattribute processing, because we want to record this exception log, Instead of just showing it to the UI interface.

2) Customexceptionattribute Global Exception:

  Public Override voidonexception (Exceptioncontext filtercontext) {intStatusCode =FilterContext.HttpContext.Response.StatusCode; if(Filtercontext.exception! =NULL&& StatusCode! =404)            {                //Write log records                stringMessage =string. Format ("----------------------------------------------------------------------------------------------------------- -------------------------------------------------\ r \ n The following is a summary of the captured exception information: \ r \ n Time: {0}\r\n message type: {1}\r\n message content: {2}\r\n method to throw exception: {3}\r\n throws Exception Source: {4}", DateTime.Now, FilterContext.Exception.GetType ().                     Name, FilterContext.Exception.Message, FilterContext.Exception.TargetSite , FilterContext.Exception.Source+filterContext.Exception.StackTrace); Dbentityvalidationexception e= Filtercontext.exception asdbentityvalidationexception; if(E! =NULL&& E.entityvalidationerrors.count () >0) {System.Text.StringBuilder tempdate=NewStringBuilder ("\ r \ n Here is the validation class details captured: \ r \ n"); foreach(varEveinche.entityvalidationerrors) {Tempdate.appendline (string. Format ("Entity of type \ "{0}\" in state \ "{1}\" has the following validation errors:", Eve. Entry.gettype (). Name, Eve.                        Entry.state)); foreach(varVeinchEve. validationerrors) {Tempdate.appendline (string. Format ("-property: \ "{0}\", Error: \ "{1}\"", Ve. PropertyName, Ve.                        errormessage)); }} message+ = Tempdate.append ("\ r \ n").                ToString (); } Task T=NewTask (() ={WL.Common.SysLogHelp.WriteLogFile ("errorlog", message, filtercontext.httpcontext);                });                T.start (); //t.wait ();            }            if(Filtercontext.result isjsonresult) filtercontext.exceptionhandled=true; Else                Base.        Onexception (Filtercontext); }

Customexceptionattribute Global exception to the method, first ruled out not 404 of the exception, because, 404 may be Dead chain, the site should not be processed, to the IIS-level exception handler processing.

IIS Configuration Administrator (Windows 2012)

There are two ' error ' handling mechanisms in IIS Configuration Manager, configuring 404 pages in. NET provisioning options, a potential problem statuscode=304 instead of 404, Microsoft has instructions, and there's no problem configuring the IIS error page!

Our above code does not handle 404 pages, if processing, then may not get statuscode=404 status code, the surface of the UI without any problems, but for the SEO, the dead chain can not be processed in a timely manner.

At the same time the above code is set filtercontext.exceptionhandled = True for Filtercontext.result is Jsonresult, and for other exception base. Onexception (Filtercontext), continue to deal with the outside, to prevent other anomalies can not be processed in time. We use task tasks to write logs asynchronously, and writing logs is a waste of time after all.

Now let's test these two anomalies, and see if the code is ' graceful ' a lot

Test Exception Log Text file

The contrast between the two pieces of code, obviously the former beautiful a lot. There is no heartbeat, quick reference to your own MVC framework it!

Summary: In the traditional Web form framework for the integration of AOP ideas is a more worrying thing, Microsoft has seen this, the new MVC framework is really a lot better than before, for our refinement of the code and design ideas in a step further, such as exception capture, authorization, etc. can also be well reflected. If you're still a former program ape, now you're feeling the sense of the designer, aren't you?

AOP-based MVC blocking exceptions make code more beautiful

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.