Problem
During application execution ASP.NET an exception may occur that is not handled in the application code, because no one is immune from errors or inattention. , But the standard page ASP.NET reporting an error is quite intimidating for the average user. The solution is to create a user-friendly interface for it.
Decision
To do this, you will need to make changes to Global. asax. This file contains methods that handle application-level and session-level events. We will need to work with the Application_Error method. In addition, you will need to create a page, let’s call it Error. aspx, that reports an error.
Global.asax.cs code
There are several possible approaches to implementing the error notification process.
1. Inform the user about the error and provide information about it. In this case, the code looks like this:]
protected void Application_Error(Object sender, EventArgs e)
{
try
{
//catching the last exception
Exception lastError = Server.GetLastError();
if (lastError != null)
{
//We write the exception that caused this one directly to
//Session for future reference
Session ["ErrorException"] = lastError. InnerException;
}
/ / Clearing the error on the server
Server. ClearError();
// Redirection to your error display page
Response.Redirect("Error.aspx");
}
catch (Exception)
{
//if we still come here, it means that exception handling
/ / generated the exception itself, we don't do anything to
/ / not create an infinite loop
Response.Write ("Unfortunately, a critical error occurred. Click the Back button in the browser and try again. ");
}
}
2. Notify the administrator
2.1. By e-mail
protected void Application_Error(Object sender, EventArgs e)
{
try
{
try
{
System.Exception ex = Server. GetLastError();
// Collecting the necessary
String data Message = "Main Error" + "nDate & Time: " +
DateTime.Now.ToString("F") + "nnURL: " + Request.Path +
"nnQUERY: " + Request.QueryString + "nnMESSAGE: " +
ex.Message + "nnBROWSER: " + Request.Browser.Browser +
"nnIP Address: " + Request.UserHostAddress;
//Adding information about the previous page visited
if(Context.Request. UrlReferrer != null)
{
Message += "nnReferer: " +
Context.Request.UrlReferrer.ToString();
}
//Adding information about the user, if the authentication process was successful
if(Context. User.Identity.IsAuthenticated)
{
Message += "nnUser: " + Context.User.Identity.Name;
}
Message += "nnnnEXCEPTION: " + ex.ToString();
System.Web.Mail.MailMessage mail = new System.Web.Mail.MailMessage();
mail.To = "[administrator's email address]";
mail.Subject = "Error in the Site";
mail.Priority = System.Web.Mail.MailPriority.High;
mail.BodyFormat = System.Web.Mail.MailFormat.Text;
mail.Body = Message;
// Here you must specify the SMTP server used
System. Web. Mail.SmtpMail. SmtpServer=" [SMTP server address]";
System. Web. Mail.SmtpMail. Send(mail);
}
catch {}
// Zeroing the error on the server
Server.ClearError();
// Redirection to a static html page that reports an error
/ / no information about the error is passed to it
Response.Redirect("Error.html");
}
catch
{
// if we still come here, it means that exception handling
/ / generated the exception itself, we don't do anything to
/ / not create an infinite loop
Response.Write ("Unfortunately, a critical error occurred. Click the Back button in the browser and try again. ");
}
2.2. By writing a message to the Windows Event Log
protected void Application_Error(Object sender, EventArgs e)
{
try
{
// Name of the resource that caused the error
string EventSourceName = "ErrorSample";
// Name of LogView
string logName = "Application";
System.Exception ex = Server.GetLastError();
System.Diagnostics.EventLog Log = new System.Diagnostics.EventLog(logName);
Log.Source = EventSourceName;
Log.WriteEntry(ex.InnerException.Message, System.Diagnostics.EventLogEntryType. Error);
/ / Zeroing the error on the server
Server. ClearError();
// Redirection to a static html page that reports an error
// no information about the error is passed to it
Response.Redirect("Error.html");
}
catch (Exception ex)
{
// if we still come here, it means that exception handling
/ / generated the exception itself, we don't do anything to
/ / not create an infinite loop
Response.Write ("Unfortunately, a critical error occurred. Click the Back button in the browser and try again. ");
}
}
Here you should note that often the app ASP.NET it has a fairly limited set of rights (which, in principle, is correct from the security point of view). Because of this, we can’t programmatically create an Event Source or check its existence in the Windows Event log if we don’t use impersonate. The solution can be to manually create an Event Source. To do this, add a new key to the registry using the regedit program.
We need to add a new key at
HKEY_LOCAL_MACHINESYSTEMCurrentControlSetServicesEventlogApplication.
Its name must match the one specified in the code. In our case, this is ErrorSample
3. Using a combination of the above methods
Error.aspx page
The Error. aspx page, as mentioned above, should directly display an error message. To do this, add a Label to it and call it lblMessage. We will handle the exception (let me remind you that we placed it in the session) in the Page_Load method. Its text is given below.
private void Page_Load(object sender, System.EventArgs e)
{
try
{
// get information about an exception from the session
Exception exc=(Exception)Session ["ErrorException"];
string ErrorMsg = exc.Message;
string pageErrorOccured = Context.Request.UrlReferrer.ToString();
string exceptionType = exc.GetType().ToString();
string stackTrace = exc.StackTrace;
// clearing the session variable
Session ["ErrorException"] = null;
//displaying a generic lblMessage error message
to the user.Text = "Unfortunately, an application execution error occurred.<br/><br/>";
lblMessage.Text =String.Format("{0} to try again,
click <a href="{1}">here</a>.<br /><br />",lblMessage.Text,
pageErrorOccured);
//adding a specific message about
lblMessage.Text = lblMessage.Text +
"Error Message: " + errorMsg +"n"+
"Page Error Occurred: " + pageErrorOccured + "n"+
"ExceptionType: " + exceptionType +"n"+
"Stack Trace: " + stackTrace;
}
catch (Exception ex)
{
//if the exception is caused by the code written above
// display an error message and StackTrace
lblMessage.Text = ex.Message+" "+ex.StackTrace;
}
}
Alternative
It should be noted that it is much more efficient to use one of the parameters of the web. config file. This will allow you to quickly (without changing the code) change the link of the page with error messages or remove it altogether, if necessary. A link to it is set using the defaultRedirect attribute. In addition, when using this attribute in the code, you should remove the lines
// Nullifying an error on the Server
Server.ClearError ();
And the need for the following lines is simply lost, since redirection now occurs automatically.
// Redirects to a page that reports
a Response error.Redirect("Error.aspx");
Example of configuring web. config:
<customErrors mode="On" defaultRedirect="error.aspx"/>
There is also an additional option: redirection to a specific page depending on the HTTP error code. The “error“parameter allows you to do this. Its statusCode attribute sets the error code, and redirect sets the page to redirect the user to. For example, if the requested resource is not found (error code 404), redirect the user to the page Error404.html, notifying the user about an incident. Web. config will look like this:
<customErrors mode="On" defaultRedirect="error.aspx">
<error statusCode="404" redirect="Error404.html"/>
</customErrors>