首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

一个比较好的.net 3.5的错误报告类

2012-12-22 
一个比较好的.net 3.5的异常报告类发现了一个比较好的异常报告类,其中用到了.net 3.5以上的扩展方法的机制

一个比较好的.net 3.5的异常报告类
发现了一个比较好的异常报告类,其中用到了.net 3.5以上的扩展方法的机制,
实现的是当有异常时,发邮件报告
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net.Mail;

namespace Experiement
{
    public static class MyExtension
    {
        public static void SendErrorEmail(this Exception ex)
        {
            MailMessage mailMessage = new MailMessage(new MailAddress("from@gmail.com")
                                       , new MailAddress("to@gmail.com"));
            mailMessage.Subject = "Exception Occured in your site";
            mailMessage.IsBodyHtml = true;

            System.Text.StringBuilder errorMessage = new System.Text.StringBuilder();

            errorMessage.AppendLine(string.Format("<B>{0}</B>:{1}","Exception",ex.Message));
            errorMessage.AppendLine(string.Format("<B>{0}</B>:{1}", "Stack Trace", ex.StackTrace));

            if (ex.InnerException != null)
            {
                errorMessage.AppendLine(string.Format("<B>{0}</B>:{1}", " Inner Exception", ex.InnerException.Message));
                errorMessage.AppendLine(string.Format("<B>{0}</B>:{1}", "Inner Stack Trace", ex.InnerException.StackTrace));
            }

            mailMessage.Body = errorMessage.ToString();

            System.Net.NetworkCredential networkCredentials = new
            System.Net.NetworkCredential("youraccount@gmail.com", "password");
           
            SmtpClient smtpClient = new SmtpClient();
            smtpClient.EnableSsl = true;
            smtpClient.UseDefaultCredentials = false;
            smtpClient.Credentials = networkCredentials;
            smtpClient.Host = "smtp.gmail.com";
            smtpClient.Port = 587;
            smtpClient.Send(mailMessage);

           
        }
    }
}

使用:
using System;

namespace Experiement
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender,System.EventArgs e)
        {
            try
            {
                throw new Exception("My custom Exception");
            }
            catch (Exception ex)
            {
                ex.SendErrorEmail();
                Response.Write(ex.Message);
            }
        }

    }
}

热点排行