Establish an error-handling strategy
Dealing with errors is an important part of every application. Web applications aren’t an exception, in the contrary, they should be even better in graceful error handling, because of their huge amount of users.
We have three possible locations of caching errors in an ASP.NET application. The first one is the source of the error itself, by wrapping our code, which is likely to fail, in a try-catch block. This is a very good solution for the problem, since the error gets treated on the spot of its occurrence. You can decide to bubble the error forth, and catch it in the Page_Error event, or even further, in the Application_Error event, defined in global.asax. There’s a fourth opportunity, but it isn’t the best solution: define custom error pages in the customErrors section of your web.config. They are part of the apologize, not the solution for the problem, so you should restrict the use of them. Even worse, when you are on a custom error page, you have no way to get and deal with the error lead you there.
Before writing error-handling code, make sure that you do everything to prevent errors from happening. The best way to do so is to use a massive amount of validation. String.Empty and the Exists method should be very close friends of you.
But if the worse happened, you should fail elegantly, and without showing any inner workings of your application. Hold the detailed error messages to server administrators, and give user-friendly and meaningless errors to the everyday users. Also, you should log the exception (Health monitoring comes handy for this task).
I think all three levels of error handling is easily understandable. However, Page_Error is a bit neglected. This event is very similar to the Application_Error event, and is a good candidate for working with errors. However, global.asax provides an encapsulated counterpart for every pages in your application. Work with Page_Error only when you need to use different error-handling strategy for that given page only, otherwise, use global.asax’s Application_Error event.