There were many chances for the occurrence of error in a .NET web application. We can easily fetch those errors and handle the users in a friendly way with the Global.asax file.
The event Application_Error in the Global.asax file deals with this. You can add this Global.asax file in the root of your web application. Inside that place the following code.
void Application_Error(object sender, EventArgs e)
{
Server.Transfer("~/CustomErrors/ErrorHandlingPage.aspx?error=" + Server.GetLastError().Message);
}
This code will fetch the last error occurred in the application and redirects to the ErrorHandlingPage.aspx. Here you can get the error message from the query string 'error'. This is how it works.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
String ErrorMsg;
ErrorMsg = Request.QueryString["error"].ToString();
LitError.Text = "Sorry for the inconvenience caused. We regret the situation. Please try after some time. The following exception occured - " + ErrorMsg;
//The below line is for publishing the error to the Exception Log - Specific to the application
ExceptionManager.Publish(ErrorMsg);
}
}
Its upto you to decide, whether to show the message to the user or make in entry in the exception log and notify user with custom error message. Thats it.
Happy coding. Have a good day.
Hey this was very useful. But these contents were too old. U pls upload something new yaar....
ReplyDelete