blog

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

Error Handling in ASP.NET

priyanka kushwaha2277 19-Feb-2015

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>
     <customErrorsmode="On"defaultRedirect="ErrorPage.aspx">
        <errorstatusCode="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.

 

        protectedvoid Application_Error(object sender, EventArgs e)
        {
 
            Exception exc = Server.GetLastError();
            if (exc isHttpUnhandledException)
            {
                // 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.

protectedvoid Page_Load(object sender, EventArgs e)
        {
            thrownewInvalidOperationException("An InvalidOperationException " +
    "occurred in the Page_Load handler on the ErrorPage.aspx page.");
        }
privatevoid Page_Error(object sender, EventArgs e)
        {
            // Get last error from the server.
            Exception exc = Server.GetLastError();
 
            // Handle specific exception.
            if (exc isInvalidOperationException)
            {
                // 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.

 

protectedvoid ErrorButton_Click(object sender, EventArgs e)
        {
            //Response.Redirect("Trial.aspx");
            thrownewInvalidOperationException();
        }
privatevoid Page_Error(object sender, EventArgs e)
        {
            // Get last error from the server.
            Exception exc = Server.GetLastError();
 
            // Handle specific exception.
            try
            {
                if (exc isInvalidOperationException)
                {
                    // 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>
    <formid="form1"runat="server">
     <asp:Labelid="Message"style="Z-INDEX: 101; LEFT: 34px;
                POSITION: absolute; TOP: 46px"runat="server"></asp:Label>
            <asp:Buttonid="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
{
    publicpartialclassDefaultPage : System.Web.UI.Page
    {
        protectedvoid Page_Load(object sender, EventArgs e)
        {
            Message.Text = "This sample page an error";
 
        }
 
 
        protectedvoid ErrorButton_Click(object sender, EventArgs e)
        {
           Response.Redirect("Trial.aspx");
        }
}
}


3.   Create a Global.asax file 

  protectedvoid Application_Error(object sender, EventArgs e)
        {
 
           Exception exc = Server.GetLastError();
          if (exc isHttpUnhandledException)
          {
          // Pass the error on to the error page.
             Server.Transfer("ErrorPage.html", true);
          }
 
        }

 

4.Create a ErrorPage.Html file

<htmlxmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<bodystyle="color:white;background-color:blue">
      ERROR PAGE
</body>
</html>


4.      Create a web.config 

<configuration>
    <system.web>
      <compilationdebug="true"targetFramework="4.5" />
      <httpRuntimetargetFramework="4.5" />
      <customErrorsmode="On"defaultRedirect="ErrorPage.html">
        <errorstatusCode="404"redirect="ErrorPage.html"/>
       </customErrors>
    </system.web>
</configuration>

Error Handling in ASP.NET

Error Handling in ASP.NET

 


Updated 19-Feb-2015

Leave Comment

Comments

Liked By