1

I'm new to ASP.NET and I have a very basic site that I just want to grab all Application Errors and email them to me, while giving the user a error page. I read a lot on the subject and seems to be a lot of information. Below is what I came up with but I'm having problems keeping the Exception in session so I can email it to me.

I keep getting a NullReferenceException was unhandled by user code on the ex.Message from the Error.aspx.cs file.

Any thoughts?

Global.asax.cs-

void Application_Error(object sender, EventArgs e)
{
    Exception ex = Server.GetLastError();

    HttpContext.Current.Response.Redirect("~/Error.aspx");
}

Error.aspx.cs-

public partial class Error : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Exception ex = (Exception)Session["Exception"];
            this.SendEmail(ex);
            Session.Remove("Exception");
        }
    }

    private void SendEmail(Exception ex)
    {
        string body = "An exception occured at "
                    + DateTime.Now.ToLongTimeString()
                    + " on " + DateTime.Now.ToLongDateString()
                    + "<br />" + ex.Message; //ERROR HERE
        MailMessage msg = new MailMessage("[email protected]", "[email protected]");
        msg.Subject = "Exception in Portal Website";
        msg.Body = body;
        msg.IsBodyHtml = true;
        SmtpClient client = new SmtpClient("localhost");
        client.Send(msg);
    }
}
0

4 Answers 4

3

Your problem is that you are never setting Session["Exception"], so on your Error.aspx, Exception ex is always going to be null... and then doing ex.Message will throw the NullReferenceException. Even if you fix that and appropriately set Session["Exception"], what you are doing isn't ideal.

  1. You could just send the email from the Application_Error function.

  2. Your Response.Redirect (MSDN Entry) is going to cause ANOTHER exception (ThreadAbortException)

  3. You should look at implementing ELMAH. It is easy to implement and does everything you want to do.

But if all you want to do is fix your code, just move the send email logic to Application_Error and then you don't have to worry about Session.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks Mike, I will look into ELMAH more, I wasn't sure what it took to get it implemented. I just wanted to use something simple (Thought it would be) for now and see how it works. I will move my email logic to Application_error and see how that works.
I used something similar to what you are doing for years, so nothing wrong with it. Can setup ELMAH in a matter of minutes though and it has some nice functionality.
@Zach but I think all you need to do is in the Visual Studio Package Manager Console, run Install-Package elmah and ELMAH will be working (logging errors in memory I believe)... needs minor massaging to put those in a DB.
1

What I did in a similar instance is to throw all exceptions and then in your global.asax uses the Application_Error method to perform any work you need to with the error message.

  void Application_Error(object sender, EventArgs e) 
    {
        // Code that runs when an unhandled error occurs
        string exception;
            Exception ex = Server.GetLastError();
            if (ex.InnerException != null)
            {
                Exception innerException = ex.InnerException;
                exception = ex.InnerException.Message;
            }
            else
            {
                exception = ex.Message;
            }

        //Send email here       

            //redirect to error page


    }

Comments

0

I don't see you pushing the exception object to session, why not move the SendEmail method to global.ascx and SendEmail then redirect user to Error page. There are third party plugins like ELMAH that can do all this easily for you with simple configurations.

Comments

0

I'm in a similar bind. I'm going to check out ELMAH, but my project has a huge restriction on Open Source Projects, yours may to. Sucks to be me!

In which case I'd suggest creating a logging function for the message that you can call directly from the Global.asax. Something like:

 void Application_Error(object sender, EventArgs e)
 {
      Exception ex = Server.GetLastError();
      LogException(ex);
      HttpContext.Current.Response.Redirect("~/Error.aspx");
 }

 //Somewhere Else
 void LogException(Exception ex)
 {
      WriteExceptionToEndOfTextFile(ex);
      SendEmail();
 }

This way if someone decides they want to suppress our exceptions, they can still properly handle the exception.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.