Partager via


How to: Handle Application-Level Errors

This code example shows how to create an error handler in the Global.asax file that will catch all unhandled ASP.NET errors while processing a request — in other words, all the errors that are not caught with a Try/Catch block or in a page-level error handler. In the example, the handler transfers control to a generic error page named GenericErrorPage.aspx, which interprets the error and displays an appropriate message.

Example

The following example is from a complete code sample in Complete Example for Error Handlers.

To enable the error event handler in the Global.asax file, the Web.config file cannot specify a file for defaultRedirect. The configuration file takes precedence. Therefore, you can either set customErrors to Off or remove the defaultRedirect setting. If your Web.config configuration file has customErrors set to Off, the Application_Error event handler in Global.asax will process all unhandled errors.

Security noteSecurity Note

Never set customErrors to Off in your Web.config file if you do not have an Application_Error handler in your Global.asax file. Potentially compromising information about your Web site can be exposed to anyone who can cause an error to occur on your site.

Robust Programming

It is better to use Try/Catch blocks around any code that is subject to errors instead of relying on a global error handler.

An error handler that is defined in the Global.asax file will only catch errors that occur during processing of requests by the ASP.NET runtime. For example, it will catch the error if a user requests an .aspx file that does not occur in your application. However, it does not catch the error if a user requests a nonexistent .htm file. For non-ASP.NET errors, you can create a custom handler in Internet Information Services (IIS). The custom handler will also not be called for server-level errors.

You cannot directly output error information for requests from the Global.asax file; you must transfer control to another page, typically a Web Forms page. When transferring control to another page, use Transfer method. This preserves the current context so that you can get error information from the GetLastError method.

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

Security

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 Page-Level Errors

Concepts

Complete Example for Error Handlers