ASP. NET mvc3 Exception Handling learning notes

Source: Internet
Author: User

ASP. NET mvc3 Exception Handling

 

In ASP. net mvc, The handleerror feature can be used to easily handle errors.

Use handleerror attribute and set customerrors in Web. config. When an unhandled exception exists in the program, it can be directed to a friendly view page.

First, we will decompile the onexception method in handleerror to see how it is implemented:

 

Public Virtual void onexception (exceptioncontext filtercontext)
{
If (filtercontext = NULL)
{
Throw new argumentnullexception ("filtercontext ");
}
If (! Filtercontext. ischildaction &&(! Filtercontext. exceptionhandled & filtercontext. httpcontext. iscustomerrorenabled ))
{
Exception innerexception = filtercontext. exception;
If (New httpexception (null, innerexception). gethttpcode () = 500) & this. exceptiontype. isinstanceoftype (innerexception ))
{
String controllername = (string) filtercontext. routedata. Values ["controller"];
String actionname = (string) filtercontext. routedata. Values ["action"];
Handleerrorinfo model = new handleerrorinfo (filtercontext. exception, controllername, actionname );
Viewresult result = new viewresult {
Viewname = This. view,
Mastername = This. Master,
Viewdata = new viewdatadictionary Tempdata = filtercontext. Controller. tempdata
};
Filtercontext. Result = result;
Filtercontext. exceptionhandled = true;
Filtercontext. httpcontext. response. Clear ();
Filtercontext. httpcontext. response. statuscode = 500;
Filtercontext. httpcontext. response. tryskipiiscustomerrors = true;
}
}

}

We can see that if an unhandled exception is not marked as "handled" and custom error handling is enabled, the error will be captured and handled here.

 

Set customerror in Web. config

 

Customerror defines automatic Exception Handling behavior, as shown below:

 

<Customerrors mode = "on" defaultredirect = "~ /Error/unknown ">

<Error statuscode = "404" Redirect = "~ /Error/notfound "/>
</Customerrors>

 

The value of mode can be off, on, or remoteonly. Different values define the actions of the R & D stage or product after release.

Use Cases of mode values:

 

  • On: Enable custom error handling.
  • Off: Disable custom error handling. When an exception occurs, the yellow pages of ASP. NET are displayed.
  • Remoteonly: if you run a program (http: // localhost) on the server, no custom exception information is displayed when an exception occurs. If you access the program through another machine, the custom exception information is displayed. This option is often used by developers to debug programs. If an exception occurs, developers can view the exception details through local access, while Remote Access Users can see custom exceptions.

Note:

If the handleerror feature is used and customerror is enabled, when an unhandled exception occurs, MVC searches for the "error" view (in the view folder corresponding to the current controler or in the shared folder) in the context of the httprequest executed and presents it to the user. In this case, customerror's "defaultredirect" and "Redirect" attributes will be invalid. Note: If the error view is not found, ultredirect and redirect are used.

 

If handleerror is not used and customerror is enabled, the URL specified by the defaultredirect and redirect attributes will be redirected when an unhandled exception occurs. In the example above, the/error/

Unknown

Tip: In ASP. N. Net mvc3, a global handleerror is registered for All controllers by default. Therefore, you do not need to worry that the controller in the application does not use handleerror. No global filter exists in earlier versions, and handleerror must be manually defined for each action or controller.

 

In customerror of Web. config, you can also set to redirect to a static page when an exception occurs, as shown below:

<Customerrors mode = "on" defaultredirect = "custom404.htm">


</Customerrors>

Note: static pages must be placed in the root directory of the web site; otherwise, they cannot be directed.

 

Methods for executing other functions during exception handling:

 

1. Rewrite the onexception method of controller.

If we need to record error logs not only when a custom error page is displayed when an exception occurs, we can inherit the Controller class and repeat the onexception method. If all the controllers in the MVC program need to record logs, you can create a basecontroller, override the onexcetion method, and then inherit the basecontroller from other controllers that need to record logs. For example:

Public class basecontroller: Controller

{

Protected override void onexception (exceptioncontext filtercontext)

{// Exception records can be recorded in the database or text, or other logging components. // Obtain this exception through filtercontext. Exception. String filepath = @ "D: \ temp \ exceptions.txt"; streamwriter Sw = system. io. file. appendtext (filepath); Sw. write (filtercontext. exception. message); Sw. close (); // execute onexception base in the base class. onexception (filtercontext );

}

}

Then other controllers inherited from basecontroller will implement the function of recording error logs.

 

2. Create filterattribute

You can use filterattribute to add it to the global filter set for the entire application. If you only need to use it in several actions, you can add this feature to the Controller action.

 

Filter is defined as follows:

Public class logexceptionfilterattribute: filterattribute, iexceptionfilter

{Public void onexception (exceptioncontext filtercontext) {// Add logging code }}

 

To apply all actions to all controllers, implement the following code in global. asax. CS:

 

public static void RegisterGlobalFilters(GlobalFilterCollection filters){    filters.Add(new LogExceptionFilterAttribute());    filters.Add(new HandleErrorAttribute());}

Or Add the following parameters to the Controller or action that only needs to use this feature:

 

 

[Logexceptionfilter ()] public actionresult about () {Throw new exception ("error .");}
 

 

 

Reference: http://www.dotneat.net/2011/04/12/ErrorHandlingInASPNETMVC3.aspx

 

 

 

Related Article

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.