Complete Example for Error Handlers
Code Example Files
- Web.config
- Global.asax
- Default.aspx
- ExceptionUtility (to be put in the App_Code folder)
- GenericErrorPage.aspx
- HttpErrorPage.aspx
- Http404ErrorPage.aspx
- DefaultRedirectErrorPage.aspx
Web.config
Note |
|---|
In the example, the mode attribute is set to "On" so that you can error messages when you run the example in Visual Studio. In a production environment, this setting would normally be "RemoteOnly". ASP.NET then renders error pages to external users. If a request is made on the server computer (localhost), ASP.NET renders a page with detailed error information.
|
Global.asax
Security Note |
|---|
Never set the mode attribute in the customErrors element to "Off" in the Web.config file if you have not created an Application_Error handler in the Global.asax file. If the mode is set to "Off," potentially compromising information about your Web site can be exposed to anyone who can cause an error to occur on your site.
|
void Application_Error(object sender, EventArgs e) { // Code that runs when an unhandled error occurs // Get the exception object. Exception exc = Server.GetLastError(); // Handle HTTP errors if (exc.GetType() == typeof(HttpException)) { // The Complete Error Handling Example generates // some errors using URLs with "NoCatch" in them; // ignore these here to simulate what would happen // if a global.asax handler were not implemented. if (exc.Message.Contains("NoCatch") || exc.Message.Contains("maxUrlLength")) return; //Redirect HTTP errors to HttpError page Server.Transfer("HttpErrorPage.aspx"); } // For other kinds of errors give the user some information // but stay on the default page Response.Write("Global Page Error
\n"); Response.Write( "" + exc.Message + "
ExceptionUtility
using System; using System.IO; using System.Web; // Create our own utility for exceptions public sealed class ExceptionUtility { // All methods are static, so this can be private private ExceptionUtility() { } // Log an Exception public static void LogException(Exception exc, string source) { // Include enterprise logic for logging exceptions // Get the absolute path to the log file string logFile = "App_Data/ErrorLog.txt"; logFile = HttpContext.Current.Server.MapPath(logFile); // Open the log file for append and write the log StreamWriter sw = new StreamWriter(logFile, true); sw.WriteLine("********** {0} **********", DateTime.Now); if (exc.InnerException != null) { sw.Write("Inner Exception Type: "); sw.WriteLine(exc.InnerException.GetType().ToString()); sw.Write("Inner Exception: "); sw.WriteLine(exc.InnerException.Message); sw.Write("Inner Source: "); sw.WriteLine(exc.InnerException.Source); if (exc.InnerException.StackTrace != null) { sw.WriteLine("Inner Stack Trace: "); sw.WriteLine(exc.InnerException.StackTrace); } } sw.Write("Exception Type: "); sw.WriteLine(exc.GetType().ToString()); sw.WriteLine("Exception: " + exc.Message); sw.WriteLine("Source: " + source); sw.WriteLine("Stack Trace: "); if (exc.StackTrace != null) { sw.WriteLine(exc.StackTrace); sw.WriteLine(); } sw.Close(); } // Notify System Operators about an exception public static void NotifySystemOps(Exception exc) { // Include code for notifying IT system operators } }
Default.aspx
<%@ Page Language="C#" %>
"-//W3C//DTD XHTML 1.0 Transitional//EN"
Default Page
Click this button to create an InvalidOperationException.Page_Error will catch this and redirect to GenericErrorPage.aspx.
Page_Error will catch this and handle the error.
runat="server" CommandArgument="2" OnClick="Submit_Click" Text="Button 2" /> Click this button to create a generic Exception.
Application_Error will catch this and handle the error.
runat="server" CommandArgument="3" OnClick="Submit_Click" Text="Button 3" /> Click this button to create an HTTP 404 (not found) error.
Application_Error will catch this and redirect to HttpErrorPage.aspx.
runat="server" CommandArgument="4" OnClick="Submit_Click" Text="Button 4" /> Click this button to create an HTTP 404 (not found) error.
Application_Error will catch this but will not take any action on it, and ASP.NET will redirect to Http404ErrorPage.aspx. The original exception object will not be available.
runat="server" CommandArgument="5" OnClick="Submit_Click" Text="Button 5" /> Click this button to create an HTTP 400 (invalid url) error.
Application_Error will catch this but will not take any action on it, and ASP.NET will redirect to DefaultRedirectErrorPage.aspx. The original exception object will not be available.
runat="server" CommandArgument="6" OnClick="Submit_Click" Text="Button 6" />
GenericErrorPage.aspx
<%@ Page Language="C#" %>
"-//W3C//DTD XHTML 1.0 Transitional//EN"
Generic Error Page
runat="server" Font-Bold="true" Font-Size="Large" />
"innerTrace"
runat="server" />
Error Message:runat="server" Font-Bold="true" Font-Size="Large" />
"exTrace"
runat="server" Visible="false" />
Return to the 'Default.aspx'> Default Page
HttpErrorPage.aspx
<%@ Page Language="C#" %>
"-//W3C//DTD XHTML 1.0 Transitional//EN"
Http Error Page
"innerTrace"
runat="server" />
Error Message:
"exTrace"
runat="server" Visible="false" />
Return to the 'Default.aspx'>Default Page
Http404ErrorPage.aspx
HTTP 404 Error Page
Standard error message suitable for file not found errors. The original exception object is not available, but the original requested URL is in the query string.Return to the 'Default.aspx'
DefaultRedirectErrorPage.aspx
DefaultRedirect Error Page
Standard error message suitable for all unhandled errors. The original exception object is not available.Return to the 'Default.aspx'
External Error not ASPX
errorMode="Custom" defaultResponseMode="ExecuteURL" existingResponse="Replace" > /> statusCode="404" responseMode="ExecuteURL" path="/Error/ErrorPage.aspx"/> statusCode="400" responseMode="ExecuteURL" path="/Error/ErrorPage.aspx"/> statusCode="403" responseMode="ExecuteURL" path="/Error/ErrorPage.aspx" /> statusCode="500" responseMode="ExecuteURL" path="/Error/ErrorPage.aspx" />
Note