Use ASP. NET 2.0 to record errors

Source: Internet
Author: User

In this article, we will record errors and exceptions on our website through a simple process. we will do this: when a program error occurs, the user is directed to a separate page. at the same time, the error will be recorded in a text file on the server. every time an error occurs, we record it every day as a log. let's look at some code.

Step 1: Create an error folder to store the error log file. right-click the site and choose create folder. name the folder "Error ". if the website does not contain Web. add. right-click site> Add new project> Web. config.

Step 2: Create an error handling code. we only need to right-click the site> Add new project> select class. rename this class to "ErrHandler. cs, and then click Add. when you do this, a dialog box will pop up, whether to save this class file in "App_Code", and we choose to accept it.

Step 3: now we are ErrHandler. class to add some features. this class is used to accept error information and save the error information in a text file. create a text file every day. if the same file name already exists, the error message will be appended to this file. otherwise, a new file is created and the error message is written to the file.

The Code is as follows:

 /// Handles error by accepting the error message     /// Displays the page on which the error occured    public static void WriteError(string errorMessage)    {        try        {            string path = "~/Error/" + DateTime.Today.ToString("dd-mm-yy") + ".txt";            if (!File.Exists(System.Web.HttpContext.Current.Server.MapPath(path)))            {                File.Create(System.Web.HttpContext.Current.Server.MapPath(path)).Close();            }            using (StreamWriter w = File.AppendText(System.Web.HttpContext.Current.Server.MapPath(path)))            {                w.WriteLine("\r\nLog Entry : ");                w.WriteLine("{0}", DateTime.Now.ToString(CultureInfo.InvariantCulture));                string err = "Error in: " + System.Web.HttpContext.Current.Request.Url.ToString() +                              ". Error Message:" + errorMessage;                w.WriteLine(err);                w.WriteLine("__________________________");                w.Flush();                w.Close();            }        }        catch (Exception ex)        {            WriteError(ex.Message);        }    }

This is our ErrHandler class. Then let's take a look at how to use this class and handle errors at the Page level (Application level.

Handle errors at Page level

In Default. in aspx, add a button control from the toolbox. name this button btnError and set the value to "Throw Handled Exception ". we will throw an exception. as long as we define a catch Block, when an Error occurs, it will be caught and registered in the Error folder. A text file uses the date of the current day as the file name. If no file exists, a new file will be created by the following code.

The code for clicking the button is as follows:

protected void btnHandled_Click(object sender, EventArgs e)    {        try        {            throw new Exception("Sample Exception");        }        catch (Exception ex)        {            // Log the error to a text file in the Error folder            ErrHandler.WriteError(ex.Message);        }    }

Now, run the program and click the button. because we have already handled errors and recorded exceptions in the code, you will find that nothing happens when you click the button. close the program and refresh the Error folder. You will see that a new file named today is created. the exception has been recorded as follows. the date and time are different on your machine.

Log Entry : 01/11/2008 23:33:46Error in:http://localhost:51087/ErrorHandling/Default.aspx. Error Message:Sample Exception__________________________

Redirecting users on unhandled errors (redirect users without handling errors)

Let's take a look at how to capture errors that have not been processed at the Application level and redirect users to a different page.

To capture errors without error handling, you only need to do the following. add a Global. asax file (right-click the project> Add New Item> Glabal. asax ). in the Application_Error () method, add the following code:

 void Application_Error(object sender, EventArgs e)    {        // Code that runs when an unhandled error occurs        Exception objErr = Server.GetLastError().GetBaseException();        string err = "Error in: " + Request.Url.ToString() +                          ". Error Message:" + objErr.Message.ToString();        // Log the error        ErrHandler.WriteError(err);            }

We noticed that by using Server. getLastError () function to catch errors. when an error is not handled, You need to redirect the user to a different page. What we need to do is to open your Web. config File, locate the <customErrors> tag, and unregister it. after the annotation is removed, the TAG should look like this:

<!--            The <customErrors> section enables configuration             of what to do if/when an unhandled error occurs             during the execution of a request. Specifically,             it enables developers to configure html error pages             to be displayed in place of a error stack trace.        -->                   <customErrorsmode="RemoteOnly"defaultRedirect="GenericErrorPage.htm">                        <errorstatusCode="403"redirect="NoAccess.htm" />                        <errorstatusCode="404"redirect="FileNotFound.htm" />                  </customErrors>

Set:

mode="RemoteOnly"tomode="On"defaultRedirect="GenericErrorPage.htm" to defaultRedirect="ErrorPage.aspx"

To:

<customErrorsmode="On"defaultRedirect="ErrorPage.aspx">                        <errorstatusCode="403"redirect="NoAccess.htm" />                        <errorstatusCode="404"redirect="FileNotFound.htm" />                  </customErrors>

This configuration file directs the user to the page named ErrorPage. aspx. We will create this error page and display some information to the user.

Right-click the website> Add New Item> Create ErrorPage. aspx, and a message is displayed on the page, prompting you that an error has occurred.

To test this function, we return to Default. aspx, add a new button, name it btnUnhandled, and set the text attribute to Throw Unhandled Exception. we will use the "Divide By Zero" exception. does not process it. we can find that catch blocks are missing. therefore, when an error occurs, the user will follow the instructions on the web. redirection set in the confg file to "ErrorPage. aspx ".

protected void btnHandled_Click(object sender, EventArgs e){      int i = 9;      int j = 0;      Respone.Write( i / j );}

Run this program and click the "Throw Unhandled Exception" button. You will find that the user is automatically redirected to the Error page, and the Error is recorded in the Error folder.

Original from: http://www.dotnetcurry.com/ShowArticle.aspx? ID = 94 & AspxAutoDetectCookieSupport = 1

  1. ASP. net mvc Tutorial: understanding models, views, and controllers
  2. ASP. net mvc Tutorial: Create a TaskList Application
  3. Practical ASP. NET skills
  4. Development of Slide playback webpage based on Microsoft ASP. net ajax framework

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.