Handleerrorattribute
Basic exception classifications in MVC:
-
-
- Action Exception T
- View Exception T,
- Service Exception T,
- Controller exception F (Exception get not reached),
- 404 Exception F (Exception get not reached)
First write the exception iexceptionfilter Extension Class (also note that the exception is the type, if the foreground of the Ajax request out of the exception, you return the HTML page Ajax is not received, So to Judge FilterContext.HttpContext.Request.isAjaxRequest ()), for true, return the JSON exception information array in the custom format:
Public voidonexception (Exceptioncontext filtercontext) {stringController = filtercontext.routedata.values["Controller"]. ToString (); stringAction = filtercontext.routedata.values["Action"]. ToString (); filtercontext.controller.viewdata["errormessage"] = FilterContext.Exception.Message;//here exception is an exception type instance//Grading: Customizing different exception categories, completing detection, and then grading if(FilterContext.HttpContext.Request.IsAjaxRequest ())//if it is an AJAX request, cannot return HTML, to return JSON exception information{Filtercontext.result=NewJsonresult () {Data=New{success=0, message="Please contact the Administrator"} }; } Filtercontext.result=NewViewResult ()//return to HTML page{ViewName="~/views/shared/error.cshtml",//page to jump after an errorViewData =FilterContext.Controller.ViewData}; Filtercontext.exceptionhandled=true;//tell the system that the exception has been handled, no more processing.}
The extension is good after the registration: The specific registration method see the previous filter three ways to register.
The first three of the 5 exceptions mentioned above can be captured and processed. But the next two kinds of exceptions how to deal with???
This is where the real global exception handling will be used:
Just a simple example, the specific use of the extension itself.
Mvc-aop (aspect-oriented programming) thought-filter iexceptionfilter-exception handling