I’m thinking of adding some code to my global.asax to my web apps to email me when there is an unhandled exception.
Current, I’m doing the following
- Writing a cookie on the user’s machine – in case they spam hit F5 and the website was restarted
- Adding an entry into system.Web.Cache –
Am I missing something? Would you do something different?
protected void Application_Error()
{
var ex = Server.GetLastError();
Server.ClearError();
if (NotInCache(ex))
{
// Email support
}
}
private static bool NotInCache(Exception ex)
{
bool returnValue = true;
if (ex != null)
{
HttpContext current = HttpContext.Current;
LogWriter.Trace(MethodBase.GetCurrentMethod(), Dfait.Diagnostics.TraceLevel.Level4, "Checking Cache for our exception");
if (current != null)
{
string key = ex.StackTrace;
string[] split = System.Text.RegularExpressions.Regex.Split(ex.StackTrace, "\r\n");
string value = "Exception Exists";
DateTime expiryDate = DateTime.Now.AddDays(1);
if (split.Length > 0)
{
key = split[0];
}
key = key.Trim();
HttpCookie remedyCookie = current.Request.Cookies[key];
if (remedyCookie == null)
{
HttpCookie newCookie = new HttpCookie(key, value);
newCookie.Expires = expiryDate;
current.Response.Cookies.Add(newCookie);
}
else
{
returnValue = false;
}
// The next block is to check the cache of the user.
object foundCache = HttpRuntime.Cache[key];
if (foundCache == null)
{
HttpRuntime.Cache.Insert(key, value, null, expiryDate, TimeSpan.Zero);
}
else
{
returnValue = false;
}
}
}
return returnValue;
}
Depending on how soon you want the exceptions you could always just log them to a file and then email the file to yourself every 10 minutes, 1 hour, 1 day and etc.
That way you don’t need to worry to much about if people spam the website as it will just be a bunch of duplicate exceptions in the file.
Once you send the file you could delete it or some how mark it as sent and then start a new file that way you only get a file emailed once there is something new to be sent.