In this article, we will record errors and exceptions in our website through a simple process. We do this: whenever a program error is encountered, the consumer is navigated to a separate page. Also, errors are logged to a text file on the server. Whenever an error occurs, We will log in the form of a daily record. Say so much, let's look at some code.
Step One: First create an error folder to hold the error log file. right mouse button site > create a new folder. Name the folder "Error". If you do not have a Web.config file in your site, add one. Right-click Site > Add new Project > Web.config.
Step two: Now we're going to create an error-handling code. We just need to right-click Site > Add New Project > select Class. Rename the class to "ErrHandler.cs" and click the Add button. When you do this, a dialog box pops up, and if you want to keep the class file in "App_Code", we choose to accept it.
Step three: Now we add some functionality to the Errhandler.class. This class is used to accept error messages and to save error messages in a text file. Create one such text file every day. If the same file name is already present, the error message is appended to the file. Creates a new file and writes the error message to the file.
The code appears 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.Curre Nt. Server.MapPath (Path)).
Close (); Using (StreamWriter w = file.appendtext (System.Web.HttpContext.Current.Server.MapPath (path)) {W.WR
Iteline ("\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 look at how to use this class and handle errors in the page level (application level).