Error Handling through Global.asax in ASP.Net
Hello Guys,
Here I am going to discuss you about some basic concept of
error handling via Global.asax file.
Do you know why we are going to use it? If no then know that it very much cases
we get error while our site is up and error occurred while visiting the site on
runtime (random error) unpredictable.
So we can create one log file to trace the error on daily
basis, and it is very much easy to trace the error.
Here are few steps to do the so:
Step: 1 Create Global.asax file
Step: 2 write the error handling code in
void
Application_Error(object sender, EventArgs e)
{
Exception
ex = Server.GetLastError().GetBaseException();
string
errorText = "Error DateTime: " + DateTime.Now + "
";
";
errorText += "**********************************************************************************";
errorText += "Error
Message: " + ex.Message + "
";
";
errorText += "Error
URL: " + Request.Url.ToString() + "
";
";
errorText += "Error
Source: " + ex.Source + "
";
";
errorText += "Target
Site: " + ex.TargetSite + "
" + "
";
" + "
";
errorText += "**********************************************************************************";
//Write the file
on server.
string
strFileName = "ErrorLog"
+ "-" + DateTime.Now.Month
+ "-" + DateTime.Now.Day
+ "-" + DateTime.Now.Year
+ ".txt";
strFileName = Server.MapPath("~") + "\\ErrorLog\\"
+ strFileName;
File.AppendAllText(strFileName,
errorText);
}
Step: 3 use the below namespace on top of the Global.asax
file
<%@ Application
Language="C#"
%>
<%@ Import Namespace="System.IO"
%>
<%@ Import Namespace="System.Net"
%>
<%@ Import
Namespace="System.Net.Mail"
%>
Step:4 Create ErrorLog directory in your website
Now you have done. Now in each and every error you will trace it in log
files.
Comments