Home > DeveloperSection > Blogs > Error Handling in ASP.NET

Error Handling in ASP.NET


.NET C#  ASP.Net 
Ratings:
0 Comment(s)
 705  View(s)
Rate this:

Error Handling in ASP.NET

In this blog I will talk about Error handling in ASP.NET

Types of Error Handling in Asp.NET

1. Code Level

2. Page Level

3. Application Level

Application Level error Handling

An exception in the application can be handled using the custom error pages.

Custom error pages are displayed depending on the ASP.NET Http status code.

Use the customErrors section in web.config.

This section lets you specify the error page to which the user should be redirected to when an handled exception propagates in the application level. This  section specifies error pages for both default error as well as Http status code  errors.

   <system.web>

     <customErrors mode="On" defaultRedirect="ErrorPage.aspx">

        <error statusCode="404" redirect="ErrorPage.aspx"/>

      </customErrors>

    </system.web>

A custom errors element has the following three modes available:

Off: Custom  Error page  are not display.

On: Custom Error page are  displayed on both local and remote machines.

Remote only: Custom Error pages are displayed on the  remote machine and an exception on the local machine.

You can trap errors that  occur anywhere in your application by adding code to the Application_Error handler in the Global.asax file.

 

        protected void Application_Error(object sender, EventArgs e)

        {

 

            Exception exc = Server.GetLastError();

            if (exc is HttpUnhandledException)

            {

                // Pass the error on to the error page.

                Server.Transfer("ErrorPage.html", true);

            }

 

        }

 

Page Level error handling:

A page-level handler returns the user to the page where the error occurred, but because instances of controls are not maintained there will no longer be anything on the page.To provide the error details to the user of the  application, you must specifically write the error detail to the page.

protected void Page_Load(object sender, EventArgs e)

        {

            throw new InvalidOperationException("An InvalidOperationException " +

    "occurred in the Page_Load handler on the ErrorPage.aspx page.");

        }

private void Page_Error(object sender, EventArgs e)

        {

            // Get last error from the server.

            Exception exc = Server.GetLastError();

 

            // Handle specific exception.

            if (exc is InvalidOperationException)

            {

                // Pass the error on to the error page.

                Server.Transfer("ErrorPage.html?handler=Page_Error%20-%20Trail.aspx",

                    true);

            }

 Code Level error handling :

An exception is a problem that arises during the execution of a program. It provides a way to transfer control from one  part of a program to another.

C# exception handling is built upon three keywords: _try, catch and throw.

Throw : A program throws an exception when a program show up. This is done using a throw keyword.

Try : A try block identifies a block of a code for which particular exceptions will be activated. It’s followed by one or more catch blocks.

Catch : A program catches an exception  with  an exception handler at the place in a program where you want to handle the problem. This is done using a catch keyword.

Finally: The finally block is used to execute a given set of statement. Whether an exception is thrown or not thrown.

 

protected void ErrorButton_Click(object sender, EventArgs e)

        {

            //Response.Redirect("Trial.aspx");

            throw new InvalidOperationException();

        }

private void Page_Error(object sender, EventArgs e)

        {

            // Get last error from the server.

            Exception exc = Server.GetLastError();

 

            // Handle specific exception.

            try

            {

                if (exc is InvalidOperationException)

                {

                    // Pass the error on to the error page.

                    Server.Transfer("ErrorPage.html?handler=Page_Error%20-%20Trail.aspx",

                        true);

                }

            }

            catch (Exception ex)

            {

               

            }

finally

            {

                Server.Transfer("ErrorPage.html");

            }

 

        }

 Example:

1.      Create a DefaultPage.aspx

<html

<body>

    <form id="form1" runat="server">

     <asp:Label id="Message" style="Z-INDEX: 101; LEFT: 34px;

                POSITION: absolute; TOP: 46px" runat="server"></asp:Label>

            <asp:Button id="ErrorButton" style="Z-INDEX: 102; LEFT: 269px;

                POSITION: absolute; TOP: 41px" runat="server"

                Text="Generate Error" OnClick="ErrorButton_Click"></asp:Button>

    </form>

</body>

</html>

2. Write code on DefaultPage.cs

 

namespace CustomErrorExample

{

    public partial class DefaultPage : System.Web.UI.Page

    {

        protected void Page_Load(object sender, EventArgs e)

        {

            Message.Text = "This sample page an error";

 

        }

 

 

        protected void ErrorButton_Click(object sender, EventArgs e)

        {

           Response.Redirect("Trial.aspx");

        }

}

}

3.      Create a Global.asax file

 

  protected void Application_Error(object sender, EventArgs e)

        {

 

           Exception exc = Server.GetLastError();

          if (exc is HttpUnhandledException)

          {

          // Pass the error on to the error page.

             Server.Transfer("ErrorPage.html", true);

          }

 

        }

 

4.Create a ErrorPage.Html file

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

    <title></title>

</head>

<body style="color:white;background-color:blue">

      ERROR PAGE

</body>

</html>

4.      Create a web.config

 

<configuration>

    <system.web>

      <compilation debug="true" targetFramework="4.5" />

      <httpRuntime targetFramework="4.5" />

      <customErrors mode="On" defaultRedirect="ErrorPage.html">

        <error statusCode="404" redirect="ErrorPage.html"/>

       </customErrors>

    </system.web>

</configuration>

 


Don't want to miss updates? Please click the below button!

Follow MindStick