[Switch] asp.net uses Global. asax to capture exception errors in the entire solution, asp. netglobal. asax
During the previous project, the exception information is handled on each page. When a page is counted, there are many try {} catch {} statement blocks, the entire code structure is not beautiful enough.
Today, I saw a post about using the global application class to help obtain exception information and using the server. transfer (''') specifies the page for receiving errors. In addition, the server is used to receive errors. getLastError () gets the previous exception source.
The Application_Error function in Global. asax is as follows:
Protected void Application_Error (object sender, EventArgs e) {// capture all exceptions in the entire solution try {Server. Transfer ("~ /Error. aspx ");} catch {}}
The Error receiving page Error. aspx obtains the exception information using the following code:
Exception ex = Server. GetLastError (). GetBaseException (); // obtain abnormal source if (ex! = Null) {Response. Write (ex. Message) ;}// clear the previous exception Server. ClearError ();
The test Exception Code in Text. aspx on the test page is as follows:
// Test whether the exception information is captured // test1 // int UserID = Convert. toInt32 (Request ["UserID"]. toString (); // test2 string Name = "aganar"; int UID = Convert. toInt32 (Name );
Run Test. on the aspx page, we can see the relevant exception information. We can clearly see that the Test. no try {} catch {} block exists on the aspx page, so we can easily capture the exception information.
How does aspnet detect exceptions in Globalasax?
Protected void Application_Error (Object sender, EventArgs e)
{
Exception ex = this. Server. GetLastError (). InnerException;
}
How to add Globalasax to the aspnet Solution
New> File> global application class