MVC-AOP (Aspect-Oriented Programming) Thought-IExceptionFilter of Filter-Exception Handling

HandleErrorAttribute

Basic exception classification in MVC:

      1. Action exception T
      2. view exception T,
      3. service exception T,
      4. Controller exception F (abnormal get can not be found),
      5. 404 Exception F (abnormal Get not available)

First write the exception IExceptionFilter extension class (also pay attention to the type of exception. If it is an exception from the ajax request in the foreground, you cannot receive the ajax when you return to the html page, so you need to judge filterContext.HttpContext.Request.isAjaxRequest()) , if true, returns an array of json exception information in custom format:

public void OnException(ExceptionContext filterContext)
        {
            string controller = filterContext.RouteData.Values["Controller"].ToString();
            string action = filterContext.RouteData.Values["Action"].ToString();
            filterContext.Controller.ViewData[ " ErrorMessage " ] = filterContext.Exception.Message; // here exception is an instance of the exception type
             // Classification: customize different exception categories, complete the detection, and then grade the processing 
            if (filterContext.HttpContext.Request .IsAjaxRequest())   // If it is an ajax request, it cannot return html, and json exception information should be returned 
            {
                filterContext.Result = new JsonResult() {
                    Data = new { success= 0 ,message= " Please contact the administrator " }
                };
            }
            filterContext.Result = new ViewResult()   // return html page 
            {
                ViewName = " ~/Views/Shared/Error.cshtml " , // Page jumped after error 
                ViewData = filterContext.Controller.ViewData
            };
            filterContext.ExceptionHandled = true ; // Tell the system that the exception has been handled, no more processing 
        }

After the expansion is completed, it is registered: for the specific registration method, see  the three registration methods of the previous Filter.

After testing, the first three types of exceptions mentioned above can be caught and handled. But how to handle the latter two exceptions???

This is where the real global exception handling comes into play:

It's just a simple example, and it needs to be extended by itself.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326099269&siteId=291194637