I wrote an article about ASP. NET global Exception HandlingArticleHttp://www.cnblogs.com/snowdream/archive/2008/07/03/1234402.html ). In ASP. net mvc, exception handling becomes easier.
Method 1: override onexception
Rewrite onexception in the Controller that requires exception handling. If the entireProgramYou can write a basecontroller, and all other controllers inherit it, And then rewrite onexception in basecontroller.
1 Protected Override Void Onexception (exceptioncontext filtercontext)
2 {
3 // Exception records can be recorded in the database or text, or other logging components.
4 // This exception is obtained through filtercontext. Exception.
5 String Filepath = @" D: \ temp \ exceptions.txt " ;
6 Streamwriter SW = System. Io. file. appendtext (filepath );
7 Sw. Write (filtercontext. Exception. Message );
8 Sw. Close ();
9
10 // Execute onexception in the base class
11 Base . Onexception (filtercontext );
12
13 // Redirect to the exception display page or execute other Exception Handling Methods
14 Response. Redirect ( " / " );
15 }
Method 2: Add actionfilter
If you only want to use Exception Processing for an action, you cannot override the onexception of the controller. However, we can write a predictionlogattribute first.
1 Namespace Snowdream. Demo. mvcexceptionlogging
2 {
3 Public Class Predictionlogattribute: handleerrorattribute
4 {
5 Public Override Void Onexception (exceptioncontext filtercontext)
6 {
7 String Filepath = @" D: \ temp \ exceptions.txt " ;
8 Streamwriter SW = System. Io. file. appendtext (filepath );
9
10
11 Sw. Write (filtercontext. Exception. Message );
12 Sw. Close ();
13
14 Base . Onexception (filtercontext );
15
16 Filtercontext. httpcontext. response. Redirect ( " / " );
17 }
18 }
19 }
20
Add the [exceptionlog] before the action to be processed, for example:
1 [Predictionlog]
2 Public Actionresult index ()
3 {< br> 4 viewdata [ " message " ] = " welcome to ASP. net mvc! " ;
5
6 return View ();
7 }
8
Sample download
This article applies to ASP. net mvc 1.0