jackncoke
jackncoke

Reputation: 2020

Trying to create custom error alerts

I tried creating my own custom error page with a twist. (Nothing original) Basically when the custom error page gets hit it will take the url of the error and the username of the person is logged in and sends me a short smtp e-mail. It actually is working great but it am getting these e-mails at crazy hours on pages that I test and i see nothing wrong with. I want to try and grab some information on why this custom error page was called so I can try and fix the problem.

Would anyone have any recommendations so I can enhance this page to give me more information.

 protected void Page_Load(object sender, EventArgs e)
    {
        string url = HttpContext.Current.Request.Url.AbsoluteUri;
        string DATETIME = DateTime.Now.ToString();
        string UserName = HttpContext.Current.User.Identity.Name.ToString();

        string fileName = Server.MapPath("_TextFiles/error.txt");
        string mailBody = File.ReadAllText(fileName);

        mailBody = mailBody.Replace("##url##", url);
        mailBody = mailBody.Replace("##DATETIME##", DATETIME);
        mailBody = mailBody.Replace("##UserName##", UserName);

        MailMessage myMessage = new MailMessage();
        myMessage.Subject = "Response from ";
        myMessage.Body = mailBody;

        myMessage.From = new MailAddress("*******n.com", "******");
        myMessage.To.Add(new MailAddress("*********.com", "******"));

        SmtpClient mySmtpClient = new SmtpClient();
        mySmtpClient.Send(myMessage);

    }

The Text file so thee is no confusion.

Hello,

Response from Error.aspx


An error occured on page ##url##

at ##DATETIME##


Username: ##UserName##

Upvotes: 0

Views: 161

Answers (1)

CoderMarkus
CoderMarkus

Reputation: 1118

I have the same basic setup with my sites, but you need to change your method a bit. If you send your email from the error page, the exception is no longer available. Here is what I do...

I extend the System.Web.UI.Page class and override the OnError method with the following:

protected override void OnError(EventArgs e)
{
    base.OnError(e);

    System.Exception ex = Server.GetLastError();
    Log.LogError("Error in Supr.CMS.Types.SuprPage", ex, Log.LogLevel.HandledExceptionFatal);
}

I now use this as my base class for all pages and I am notified on all errors with complete details. I include the exception message and stack trace and some user info (including IP address and UserAgent), the cookie collection, session collection, forms collection and cache collection so I know as best as possible the state of the site when the user encountered the error (a little too much to post here).

Another note... A lot of the errors are generated by bots and having info like the IP and UserAgent allow me to break that down and enhance my request blocking.

Upvotes: 2

Related Questions