在软件、网站中难免会出现种种异常,如果你的项目中有未处理的异常并且不想一处处的加异常那么可以借鉴下一下这个方案
1.新建一个全局应用文件Global.asax此文件在统计在线人数的时候应用较多
2.此文件中有个Application_Error方法此方案就是用的这个方法,加入以下捕获异常的代码
1 //在出现未处理的错误时运行的代码
2 Exception ex = Server.GetLastError();
3 StringBuilder sb = new StringBuilder();
4 string dt = DateTime.Now.ToString();
5 sb.Append("------\r\n").Append(dt).Append("\r\n内部错误:").Append(ex.InnerException.ToString())
6 .Append("\r\n堆栈:").Append(ex.StackTrace).Append("\r\n内容:").Append(ex.Message)
7 .Append("\r\n来源:").Append(ex.Source).Append("\r\n");
8 Log.SetLog(sb.ToString());
9 Server.ClearError();
10 Server.Transfer("error.aspx", false);
3.新建个记录日志并且自动发送邮件提醒的类
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Web;
5 using System.IO;
6 using System.Threading;
7 /// <summary>
8 ///Log 的摘要说明
9 /// </summary>
10 public class Log
11 {
12 public Log()
13 {
14 //
15 //TODO: 在此处添加构造函数逻辑
16 //
17 }
18 private string logBody;
19 public string LogBody
20 {
21 get { return logBody; }
22 set { logBody = value; }
23 }
24 public static void SetLog(string str)
25 {
26 string path = HttpContext.Current.Server.MapPath("log.log");
27 File.AppendAllText(path, str);
28 //Thread.Sleep(1000);
29 Log log1 = new Log();
30 log1.LogBody = str;
31 Thread t = new Thread(new ThreadStart(log1.SendEmail));
32 t.IsBackground = true;
33 t.Start();
34 }
35
36 private void SendEmail()
37 {
38 System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient();
39 client.Host = "---";
40 client.UseDefaultCredentials = false;
41 client.Credentials = new System.Net.NetworkCredential("---", "---");
42 client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
43 client.Timeout = 9000;
44 System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage("---", "---");
45 message.Subject = "---";
46 message.Body = logBody;
47 message.BodyEncoding = System.Text.Encoding.UTF8;
48 message.IsBodyHtml = true;
49
50 try
51 {
52 client.Send(message);
53
54 }
55 catch(Exception ex)
56 {
57 }
58 }
59 }
其中---按需求自行填写
4.新建个error.aspx文件用于捕获异常后转向的提示页面
-------------------------------------------------------------
生命不息,挖坑不止!