Friday, July 24, 2009

Simple Error Reporting

This should be a no-brainer, but every ASP.NET application you put out there should have some solid error reporting behind it. The simplest way you can do this is by sending an email message each time there is an error. Nothing like debugging an error before the customer even contacts you about it. Code below.

You'll want to put the following in your Global.asax file:

VB.NET:

Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)

If Request.ServerVariables("server_name") <> "localhost" AndAlso InStr(Request.Url.ToString, "get_aspx_ver.aspx") = 0 AndAlso InStr(Request.Url.ToString.ToLower(), "webresource.axd") = 0 AndAlso InStr(Request.Url.ToString.ToLower(), "scriptresource.axd") = 0 Then

' only run this if it's NOT the localhost and it's a real error - don't care about webresource.axd or scriptresource.axd errors since those don't usually show themselves to the end user

Dim objErr As Exception = Server.GetLastError.GetBaseException

Dim err As String

err = "<p><b>Error caught in Application_Error event:</b></p>"
err = err & "<p>Error URL: " & Request.Url.ToString & "</p>"
err = err & "<p>Error Message: " & objErr.Message.ToString & "</p>"
err = err & "<p>Source: " & objErr.Source.ToString & "</p>"
err = err & "<p>Stack Trace: " & objErr.StackTrace.ToString & "</p>"
err = err & "<p>Client IP Address: " & Request.ServerVariables("REMOTE_ADDR") & "</p>"

Server.ClearError()


Dim objMail As System.Net.Mail.SmtpClient = New System.Net.Mail.SmtpClient("your.smtp.server")
Dim mailFrom As System.Net.Mail.MailAddress = New System.Net.Mail.MailAddress("from@somewhere.com", "Error")
Dim mailTo As System.Net.Mail.MailAddress = New System.Net.Mail.MailAddress("to@somewhere.com")
Dim mailMsg As System.Net.Mail.MailMessage = New System.Net.Mail.MailMessage(mailFrom, mailTo)
mailMsg.Subject = "Error"

mailMsg.Body = err
mailMsg.IsBodyHtml = True
objMail.Send(mailMsg)

' redirect to a friendly error page
Response.Redirect("~/Error.htm")

End If

End Sub


C#:

void Application_Error(object sender, EventArgs e) 
{
// Code that runs when an unhandled error occurs

string url = Request.Url.ToString();

if (Request.ServerVariables["server_name"] != "localhost" && url.IndexOf("get_aspx_ver.aspx", 0) == -1 && url.IndexOf("WebResource.axd", 0) == -1 && url.IndexOf("ScriptResource.axd", 0) == -1)
{
Exception objErr = Server.GetLastError().GetBaseException();

string err = "<p><b>Error caught in Application_Error event:</b></p>";
err += "<p>Error URL: " + Request.Url.ToString() + "</p>";
err += "<p>Error Message: " + objErr.Message.ToString() + "</p>";
err += "<p>Source: " + objErr.Source.ToString() + "</p>";
err += "<p>Stack Trace: " + objErr.StackTrace.ToString() + "</p>";
err += "<p>Client IP Address: " + Request.ServerVariables["remote_addr"].ToString() + "</p>";

Server.ClearError();

' add your own email code here

Response.Redirect("~/Error.htm");
}
}

No comments:

Post a Comment