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).