7.3. Handling Errors at the Application Level
Problem
You want to report and log all errors in a common location, regardless of where they arise within the application.
Solution
Incorporate the error handling in methods (described in Recipe 7.1), add code to the
Page_Error event handler to rethrow the page
errors, and add the code to the Application_Error
event handler to perform the logging and redirection.
In the code-behind class for your ASP.NET pages that need to perform error handling, use the .NET language of your choice to:
Create a
Page_Errorevent handler.Rethrow the page errors from within the method (this is needed to avoid all errors being wrapped with an
HttpUnhandledExceptionexception).
In the code-behind for global.asax, use the .NET
language of your choice to:
Create an
Application_Errorevent handler.Create a detailed message and write it to the event log.
Redirect the user to the error page using
Server.Transfer.
The code we’ve written to demonstrate this solution
is shown in Example 7-6 through Example 7-9. The Page_Error code
required in all pages is shown in Example 7-6 (VB)
and Example 7-7 (C#). The
Application_Error code required in the
global.asax code-behind is shown in Example 7-8 (VB) and Example 7-9 (C#).
(Because the .aspx file for this example
contains nothing related to the error handling, it is not included
here.)
Discussion
The exception model in ASP.NET provides the ability for exceptions to be handled at any level, from the method level to the application ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access