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.
The following example is from a complete code sample in.
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
Off or remove the
defaultRedirect setting. If your Web.config configuration file has
customErrors set to
Application_Error event handler in Global.asax will process all unhandled errors.
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, usemethod. This preserves the current context so that you can get error information from the method.
After handling an error, you must clear it by calling themethod of the Server object ( class).
Be sure that you do not display error information that might help malicious users compromise your application. For details, see.