Application level and page level exceptional handling in ASP.NET
Author: Aadil
In this article I’ll try to explain how you can use the exception handling procedures supplied in the ASP.NET page framework to handle exceptions at page and application levels.
We remember from the old classic ASP that the global.asa file can give us access with application level events like the starting and ending of user sessions and applications. When ASP.NET was released it provided us with additional events like handing the begin request and end request methods and the Application_OnError method.
This method is the place where you can provide some code that can manage the unhandled exception that occurs from all over your web pages. You can just start adding these errors in a log file or send them directly to your email address so that you can instantaneously know that some error occurred in your web application.
There is also this facility in an asp.net web page that you can handle all the unhandled exceptions that occur in this page be handled in a page level procedure. This procedure needs to be overridden and is called OnError. When you override this procedure you need to get to the error that occurred. The server page level variable that refers to the ServerUtility object provides a GetLastError() method that points to the last error occurred. You can access the last error occurred and cast it to Exception object and get its error message for display.
You also need to call the Server.ClearError() to clear the last error occurred or the page will show the error stack trace on the web page. You can also display some textual message using response.write to display some error information to the end user.
I’ve worked out a simple page in which I threw an application exception and override the OnError page level error handler and caught and displayed the error. Here is the code.