sábado, 17 de noviembre de 2018

Complete Example for Error Handlers Aspx

Complete Example for Error Handlers

Original Microsoft Page: https://msdn.microsoft.com/es-mx/library/bb397417.aspx
This code example includes elements for both page-level and application-level exception handling.

Code Example Files

The example consists of the following 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

The following example shows the Web.config file. The customErrors section specifies how to handle errors that occur with file types that are mapped to ASP.NET, such as .aspx, .asmx, and .ashx files. (In IIS 6.0 and in IIS 7.0 in classic mode, static content files such as .html and .jpg files are not mapped to ASP.NET.)
The settings in the example customErrors section cause any unhandled HTTP 404 (file not found) errors to be directed to the Http404ErrorPage.aspx file. These HTTP 404 errors would occur if a request were made for an .aspx file, .asmx file, and so on and if the requested file did not exist. All other unhandled errors in ASP.NET files are directed to the DefaultRedirectErrorPage.aspx file.
If static content files are not handled by ASP.NET, a request for a nonexistent .html or .jpg file does not cause a redirect to the Http404ErrorPage.aspx file. If you want ASP.NET to handle requests for all file types, you can configure IIS to map file-name extensions to ASP.NET.
Note 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.
Internal Error

Global.asax

The following example shows the Global.asax file
Security note 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 + "
\n"); Response.Write("Return to the " + "Default Page\n"); // Log the exception and notify system operators ExceptionUtility.LogException(exc, "DefaultPage"); ExceptionUtility.NotifySystemOps(exc); // Clear the error from the server Server.ClearError(); }

ExceptionUtility

The following example shows the ExceptionUtility file. Error logs might be directed to the computer's ErrorLog file, or, if the computer is part of a Web farm, the error log might be recorded in a globally available text file, or even a database. You might also need to immediately notify system administrators of a problem.
The ExceptionUtility class in the example has two static methods: one to log the exception, and one to notify system administrators. How those methods are implemented in your code depends on the needs of your organization. For this example, you must grant write permissions to the ASP.NET worker process account (by default, this is NETWORK SERVICE) for the App_Data folder to enable the application to write to the error log.

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

The following example shows the Default.aspx page. This file provides several buttons, each of which raises a different exception. The Page_Errorhandler on the page displays an error page and logs some of these errors. Unhandled errors are passed to the Application_Error handler in the Global.asax file. The Application_Error handler displays an error page and logs some of the remaining errors. Any errors that are still not handled are directed to the page indicated by the customErrors section of Web.config file.

<%@ Page Language="C#" %>



"-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> "Head1" runat="server"> Exception Handler Page
"form1"
runat="server">

Default Page

Click this button to create an InvalidOperationException.
Page_Error will catch this and redirect to GenericErrorPage.aspx.
"Submit1"
runat="server" CommandArgument="1" OnClick="Submit_Click" Text="Button 1" /> Click this button to create an ArgumentOutOfRangeException.
Page_Error will catch this and handle the error.
"Submit2"
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.
"Submit3"
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.
"Submit4"
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.
"Submit5"
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.
"Button1"
runat="server" CommandArgument="6" OnClick="Submit_Click" Text="Button 6" />

GenericErrorPage.aspx

The following example shows the GenericErrorPage.aspx page. This page creates a safe message that it displays to remote users. For local users (typically developers and testers of the application), the page displays a complete exception report. The Page_Error handler redirects InvalidOperationException errors to this page.

<%@ Page Language="C#" %>



"-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> "Head1" runat="server"> Generic Error Page
"form1"
runat="server">

Generic Error Page

"InnerErrorPanel"
runat="server" Visible="false"> Inner Error Message:
"innerMessage"
runat="server" Font-Bold="true" Font-Size="Large" />
        "innerTrace"
runat="server" /> Error Message:
"exMessage"
runat="server" Font-Bold="true" Font-Size="Large" />
      "exTrace"
runat="server" Visible="false" />
Return to the 'Default.aspx'> Default Page

HttpErrorPage.aspx

The following example shows the HttpErrorPage.aspx page. This page also creates a safe message that depends on the value of the error code, which it displays to remote users. For local users, the page displays a complete exception report. The Application_Error handler redirects HttpException errors to this page.

<%@ Page Language="C#" %>



"-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> "Head1" runat="server"> Http Error Page
"form1"
runat="server">

Http Error Page

"InnerErrorPanel"
runat="server" Visible="false"> "innerMessage" runat="server" Font-Bold="true" Font-Size="Large" />
        "innerTrace"
runat="server" /> Error Message:
"exMessage" runat="server" Font-Bold="true" Font-Size="Large" />
      "exTrace"
runat="server" Visible="false" />
Return to the 'Default.aspx'>Default Page

Http404ErrorPage.aspx

The following example shows the Http404ErrorPage.aspx page. ASP.NET redirects unhandled HTTP 404 (file not found) errors to this page. The page displays the same message to remote and local users.

<%@ Page Language="C#" %>



"-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> "Head1" runat="server"> HTTP 404 Error Page
"form1"
runat="server">

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'
> Default Page

DefaultRedirectErrorPage.aspx

The following example shows the DefaultRedirectErrorPage.aspx page. ASP.NET redirects any unhandled errors except HTTP 404 errors to this page. The page displays the same message to remote and local users.
<%@ Page Language="C#" %>



"-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> "Head1" runat="server"> DefaultRedirect Error Page
"form1"
runat="server">

DefaultRedirect Error Page

Standard error message suitable for all unhandled errors. The original exception object is not available.

Return to the 'Default.aspx'
> Default Page



External Error not ASPX

The following example shows the DefaultRedirectErrorPage.aspx page. ASP.NET redirects any unhandled errors except HTTP 404 errors to this page. The page displays the same message to remote and local users.

    
     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" />
    







0 comentarios:

Publicar un comentario