MVC records exceptions by inheriting Handleerrorattribute, using log4net or elmah components, etc.

Source: Internet
Author: User
Tags log4net

Interface

public interface Iexceptionfilter {void onexception (Exceptioncontext filtercontext);}

Exceptioncontext inherits from ControllerContext, where it can obtain route data, HttpContext.

-The Handleerrorattribute is the implementation of the Iexceptionfilter, which is enabled by default

public static void Registerglobalfilters (Globalfilterscollection filters) {filters. ADD (New Handleerrorattribute ()); }

Use the default Handleerrorattribute

-Make shared/error.cshtml error page error

As a prerequisite, configure in Web. config:

<customerrors mode= "on" ></customErrors>

-Display different error pages based on different error types

[HandleError (Exceptiontype = typeof (Dbexception), View = "")] [HandleError (Exceptiontype = typeof (ApplicationException), View = "")] public actionresult someaction ()

The shortcomings of-handleerrorattribute

1. Only error page is displayed, error log 2 cannot be logged, only 500 error 3 can be captured, errors other than controller cannot be captured

Inherit Handleerrorattribute Custom Exception handling

Use Log4net to log error logs and to log Ajax errors, returning a service-side error with a status code of 500.

You need a class that displays the error message:

Namespace Mvcapplication1.models {public class Handleerrorinfo {public Handleerrorinfo (Exception Excepti On, string actionname, String controllername) {this.             Exception = Exception; This.             Controllername = Controllername; This.         ActionName = ActionName;         public string ActionName {get; set;}         public string Controllername {get; set;}     Public Exception Exception {get; set;} } }

Referencing the Log4net component, inherits the Handleerrorattribute custom exception so that it can record a service-side error with a status code of 500 and can return an AJAX-related exception in JSON form.

Using System.Web;
Using SYSTEM.WEB.MVC;
Using Log4net;
Namespace Mvcapplication1.extension
{
    Class Powerfulhandleerrorattribute:handleerrorattribute
    {
        ReadOnly ILog _logger;
        Public Powerfulhandleerrorattribute ()
        {
            _logger = Logmanager.getlogger ("MyLogger");
        }
        void Onexception (Exceptioncontext filtercontext)
        {
            if (filtercontext.exceptionhandled | |!filtercontext.httpcontext.iscustomerrorenabled)
            {
                Return
            }
            if (new HttpException (null, filtercontext.exception). Gethttpcode ()! =) 
            {
                Return
            }
            if (! Exceptiontype.isinstanceoftype (filtercontext.exception))
            {
                Return
            }
            If the AJAX request returns JSON
            if (filtercontext.httpcontext.request.headers["XMLHttpRequest")
            {
                New Jsonresult ()
                {
                    Jsonrequestbehavior = Jsonrequestbehavior.allowget,
                    New
                    {
                        True
                        message = FilterContext.Exception.Message
                    }
                };
            }
            Else
            {
                var controllername = (string) filtercontext.routedata.values["Controller"; 
                var actionname = (string) filtercontext.routedata.values["Action"]; 
                New Handleerrorinfo (Filtercontext.exception, Controllername, ActionName);
                New ViewResult ()
                {
                    ViewName = View,
                    Mastername = Master,
                    New Viewdatadictionary (model),
                    TempData = FilterContext.Controller.TempData
                };
            }
            _logger. Error (FilterContext.Exception.Message, filtercontext.exception);
            True
            FilterContext.HttpContext.Response.Clear ();
            FilterContext.HttpContext.Response.StatusCode = 500;
            True
        }
    }
}

Above Powerfulhandleerrorattribute error, can only handle service side status code 500 error. You can also set in global: Returns the corresponding Error alert view when a HttpException exception occurs.

       Handling Errors in Filter omission
        void Application_Error (object sender, EventArgs e)
        {
            var HttpContext = ((mvcapplication) sender). Context;
            var currentroutedata = RouteTable.Routes.GetRouteData (new Httpcontextwrapper (HttpContext));
            "";
            "";
            Null
            {
                if (currentroutedata.values[null &&
                    ! string. IsNullOrEmpty (currentroutedata.values["Controller"). ToString ())) 
                {
                    Currentcontroller = currentroutedata.values["Controller"]. ToString ();
                }
                if (currentroutedata.values[null &&
                    ! string. IsNullOrEmpty (currentroutedata.values["action"]. ToString ())) 
                {
                    Currentaction = currentroutedata.values["Action"]. ToString ();
                }
            }
            var ex = Server.GetLastError ();
            New Errorcontroller ();
            New Routedata ();
            "Index";
            Is HttpException)
            {
                As HttpException;
                Switch (Httpex.gethttpcode ())
                {
                    Case 404:
                        "NotFound";
                        Break
                    Default
                        "Index";
                        Break
                }
            }
            Httpcontext.clearerror ();
            HttpContext.Response.Clear ();
            Is HttpException? ((HttpException) ex). Gethttpcode (): 500;
            True
            routedata.values["Error";
            routedata.values["action"] = action;
            New Handleerrorinfo (ex, Currentcontroller, currentaction);
            ((IController) controller). Execute (new RequestContext (new Httpcontextwrapper (HttpContext), Routedata)); 
        }

To do this, you also need to define a errorcontroller and, of course, a corresponding error-prompt view:

Using SYSTEM.WEB.MVC;
Namespace Mvcapplication1.controllers
{
    Class Errorcontroller:controller
    {
        Public ActionResult Index ()
        {
            return View ();
        }
        Public ActionResult NotFound ()
        {
            return View ();
        }
    }
}

Using Elmah to record global exceptions

Using SYSTEM.WEB.MVC;
Using Elmah;
Namespace Mvcapplication1.extension
{
    Class Elmahhandleerrorattribute:handleerrorattribute
    {
        void Onexception (Exceptioncontext filtercontext)
        {
            Base. Onexception (Filtercontext);
            if (filtercontext.exceptionhandled)
            {
                Errorsignal.fromcurrentcontext (). Raise (filtercontext.exception);
            }
        }
    }
}
Exception handling in ASP.

MVC records exceptions by inheriting Handleerrorattribute, using log4net or elmah components, etc.

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.