How to: Handle Page-Level Errors

If possible, you should handle errors in Try/Catch blocks within your code, because a problem is more easily corrected where it occurs. If the user can help correct a problem, the page needs to return to the same place so the user has a context for understanding what to do.

A page-level handler returns you to the page, but there is no longer anything on the page because instances of controls are not created. To provide the user any information, you must specifically write it to the page.

You would probably use a page-level error handler to log unhandled errors or to take the user to a page that can display helpful information.

This code example shows a handler for the Error event in an ASP.NET Web page. This handler catches all exceptions that are not already handled within Try/Catch blocks in the page.

After you handle an error, you must clear it by calling the ClearError method of the Server object (HttpServerUtility class).

Example

This handler filters for specific kinds of exceptions. For an ArgumentOutOfRangeException exception, the handler writes some text on the page, provides a link back to the page, logs the error, and notifies system administrators. For an InvalidOperationException exception, the handler simply transfers the exception to the Generic Error Page. For any other kind of exception, the handler does nothing, which allows your site to automatically redirect to the generic page specified in the Web.config file. Your own code would filter for exceptions that are important to your application.

The following example is part of a complete code sample in Complete Example for Error Handlers

Security

Use the <customErrors> Element to restrict display of detailed error messages to local users only.

Be sure that you do not display error information that might help malicious users compromise your application. For details, see How to: Display Safe Error Messages.

See Also

Tasks

How to: Handle Application-Level Errors

Concepts

Complete Example for Error Handlers