使用异常c#

时间:2016-06-09 13:38:24

标签: c# c#-4.0

我正在使用smtp发送电子邮件。我在catch中使用了InnerException属性来处理异常。我的问题是我总是得到一个错误"对象引用未设置为对象的实例"每次它捕获异常?

 catch 
        {  

    HttpException ErrorType = Server.GetLastError() as HttpException;

                Exception Error = ErrorType;
          //Error line Object reference not set to an instance of an object.
                if (ErrorType.InnerException != null)
                Error = ErrorType.InnerException;
                string ErrorName = Error.GetType().ToString();
                string ErrorMessage = Error.Message;
                string ErrorTrace = Error.StackTrace;

                const string ToAddress = "mail";
                const string FromAddress = "mail";
                const string Subject = "An error has just occurred!";

                // Mail Object

                MailMessage Mail = new MailMessage("mail", "mail");
                Mail.Subject = "Error has ocurred!";
                Mail.IsBodyHtml = true;
                Mail.Priority = MailPriority.High;
                Mail.Body = string.Format(@"

  <html>
      <body>
      <h1>An Error / Exception has just occurred </h1>
     <table cellpadding=""5"" cellspacing=""0"" border=""1"">
     <tr>
      <tdtext-align: right;font-weight: bold"">URL:</td>
      <td>{0}</td>
      </tr>
        <tr>
          <tdtext-align: right;font-weight: bold"">User:</td>
        <td>{1}</td>
       </tr>
      <tr>
    <tdtext-align: right;font-weight: bold"">Exception Type:</td>
     <td>{2}</td>
      </tr>
        <tr> 
          <tdtext-align: right;font-weight: bold"">Message:</td>
        <td>{3}</td>
      </tr>
    <tr>
  <tdtext-align: right;font-weight: bold"">Stack Trace:</td>
  <td>{4}</td>
    </tr> 
      </table>
      </body>
          </html>",
            Request.RawUrl,
            User.Identity.Name,
            ErrorName,
            ErrorMessage,
            ErrorTrace.Replace(Environment.NewLine, "<br />"));
                // Death Screen
                string Markup = ErrorType.GetHtmlErrorMessage();
                if (!string.IsNullOrEmpty(Markup))
                {

                    Attachment attach = 
       Attachment.CreateAttachmentFromString(Markup, "attach.htm");
                     Mail.Attachments.Add(attach);

                }

                // Send the exception mail
                SmtpClient smtp = new SmtpClient();
                smtp.Send(Mail);
                //lblMsg.Text = "Error!";
            }

    }

1 个答案:

答案 0 :(得分:0)

如果LastServerError不是HTTPException怎么办?在这种情况下调用Server.GetLastError() as HttpException将为您提供nul l。