-->

How to create an error handler and Keep error logs file in ASP.NET C#?





Introduction

In this post I am explain how to create an error handler, Keep error logs in ASP.NET C#?

What happens if a Web a page throws an exception? By default, most exceptions are translated into an HTTP response with status code 500, Internal Server Error. And this unfriendly technical error messages generated by IIS or ASP.NET is not understandable to the normal user and is worst practices.

Regardless of the error, I want my application to give the user a "graceful" response and also I want to keep errors logs in a text file for every unhandled exception.

Steps :

Steps for create an error handler, Keep error logs file.

Step-1 : Create New Project

Go to File > New > Project > Select asp.net web forms application > Entry Application Name > Click OK.

Step-2: Add a Webpage and Design.

Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > New item > Select web form/ web form using master page under Web > Enter page name > Add.

In this page, I have added a button for through exception for test our application working or not.
HTML Code

     <h3>Create Error handler and Keep Error logs.</h3>
    <div>
        <asp:Button ID="btnException" runat="server" Text="Through Exception" OnClick="btnException_Click" />
    </div>
        
Write the below code into button click event.

        protected void btnException_Click(object sender, EventArgs e)
        {
            // Here through exception for test
            throw new InvalidOperationException();
        }
        

Step-3: Add a Webpage and Design for Show "Error" Message.

Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > New item > Select web form/ web form using master page under Web > Enter page name > Add.

In this page, I have added a Page named "ErrorPage.aspx" for show error message.

Step-4: Add a Webpage and Design for Show "Page not found" Message.

Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > New item > Select web form/ web form using master page under Web > Enter page name > Add.

In this page, I have added a Page named "PageNotFound.aspx" for show page not found message.

STEP-5: Add a folder for save file contain Error Details.

Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > New Folder > Rename folder.

Here I have added a folder named "Errors" for save text files contain error details.

Step-6: Write code for handle exception.

Write below code into Application_Error event of Global.asax for Redirect user to a page containing proper error message, generate error logs file and save.

         void Application_Error(object sender, EventArgs e)
        {
            // Code that runs when an unhandled error occurs
            HttpContext con = HttpContext.Current;
            var v = Server.GetLastError();

            var HttpEx = v as HttpException;
            if (HttpEx != null && HttpEx.GetHttpCode() == 404)
            {
                // Invalid URL
                Server.Transfer("~/PageNotFound.aspx");
            }
            else
            {
                // Exception 
                StringBuilder sb = new StringBuilder();
                sb.AppendLine("Page :           " + con.Request.Url.ToString());
                sb.AppendLine("Error Message :  " + v.Message);
                sb.AppendLine("Inner Message :  " + v.InnerException.ToString());

                // Here save text file containing this error details
                string fileName = Path.Combine(Server.MapPath("~/Errors"), DateTime.Now.ToString("ddMMyyyyhhmmss") + ".txt");
                File.WriteAllText(fileName, sb.ToString());
                Server.Transfer("~/ErrorPage.aspx");
            }
        }
        

Step-7: Run Application.

Default Error page


Our Error Page
Page Not Found Page

If you like this post please give me +1. Thank you.

Related Post:


Hello ! My name is Sourav Mondal. I am a software developer working in Microsoft .NET technologies since 2010.

I like to share my working experience, research and knowledge through my site.

I love developing applications in Microsoft Technologies including Asp.Net webforms, mvc, winforms, c#.net, sql server, entity framework, Ajax, Jquery, web api, web service and more.