自定义捕捉异常并记录到数据库模块【CoreException】

前言:这篇文章就是【.NET开发手记】里未公开的CoreExcetion模块,本人菜鸟,请高手高抬贵口不要骂我写的垃圾。

好吧,废话不多说了,代码说话!

一、首先定义一个模型类,用于存储各个异常属性,对应于数据库中得字段

数据库定义在这里:

自定义捕捉异常并记录到数据库模块【CoreException】_第1张图片

 

 1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5
6 namespace DotNetProject
7 {
8 public class ExceptionLogModel
9 {
10 #region "Property"
11 /*
12 * 输入代码:
13 * ID:int,ExceptionType:string,ExceptionDescription:string,ExceptionUser:string,ExceptionLogTime:DateTime
14 *以下是我自己写的属性生成器生成的代码,需要的找我要
15 */
16 private int _ID = 0;
17 private string _ExceptionType = string.Empty;
18 private string _ExceptionDescription = string.Empty;
19 private string _ExceptionUser = string.Empty;
20 private DateTime? _ExceptionLogTime = DateTime.Now;
21 private bool _EnabledAlert = false;
22
23 ///
24 /// 日志ID
25 ///

26 public int ID
27 {
28 get { return _ID; }
29 set { _ID = value; }
30 }
31 ///
32 /// 日志类型
33 ///

34 public string ExceptionType
35 {
36 get { return _ExceptionType; }
37 set { _ExceptionType = value; }
38 }
39 ///
40 /// 日志描述
41 ///

42 public string ExceptionDescription
43 {
44 get { return _ExceptionDescription; }
45 set { _ExceptionDescription = value; }
46 }
47 ///
48 /// 日志操作人
49 ///

50 public string ExceptionUser
51 {
52 get { return _ExceptionUser; }
53 set { _ExceptionUser = value; }
54 }
55 ///
56 /// 日志记录时间
57 ///

58 public DateTime? ExceptionLogTime
59 {
60 get { return _ExceptionLogTime; }
61 set { _ExceptionLogTime = value; }
62 }
63 ///
64 /// 确定是否发邮件通知管理员
65 ///

66 public bool EnabledAlert
67 {
68 get { return _EnabledAlert; }
69 set { _EnabledAlert = value; }
70 }
71 #endregion
72 }
73 }

二、我用桥接模式编写的这个模块,首先咱们来定义一个抽象类:

 1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5
6 namespace DotNetProject
7 {
8 public abstract class AbstractExceptionLog:Exception
9 {
10 public ExceptionLogModel Model { get; set; }
11
12 ///
13 /// 插入记录
14 ///

15 public abstract void Insert();
16 ///
17 /// 删除全部
18 ///

19 public abstract void Delete();
20 ///
21 /// 删除指定ID
22 ///

23 ///
24 public abstract void Delete(int id);
25 ///
26 /// 根据IDlist删除多条项目
27 ///

28 ///
29 public abstract void Delete(string idlist);
30 ///
31 /// 获取指定ID记录
32 ///

33 ///
34 ///
35 public abstract ExceptionLogModel getItem(int id);
36 ///
37 /// 获取所有记录的列表
38 ///

39 ///
40 public abstract System.Data.DataSet getItems();
41 }
42 }

三、有了抽象类,咱们就要实现这个抽象类,来这里:

  1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 using System.Data.SqlClient;
6 using System.Data;
7 using System.Configuration;
8 using System.Web.UI.WebControls;
9
10 namespace DotNetProject
11 {
12 using System.Reflection;
13
14 public class CoreException : AbstractExceptionLog
15 {
16 ///
17 /// SQL连接字符串
18 ///

19 private string ConnectionString
20 {
21 get
22 {
23 return ConfigurationManager.AppSettings["ConnectionString"].ToString();
24 }
25 }
26
27 ///
28 /// 插入日志记录
29 ///

30 public override void Insert()
31 {
32 using (SqlConnection connection = new SqlConnection(ConnectionString))
33 {
34 try
35 {
36 StringBuilder sql = new StringBuilder();
37 sql.Append("INSERT INTO tbExceptionLog (ExceptionDescription,ExceptionType,ExceptionUser,ExceptionLogTime,EnabledAlert)");
38 sql.Append("VALUES ('" +
39 base.Model.ExceptionDescription + "','" +
40 base.Model.ExceptionType + "','" +
41 base.Model.ExceptionUser + "','" +
42 base.Model.ExceptionLogTime + "'," +
43 (base.Model.EnabledAlert ? "1" : "0") + ")");
44
45 using (SqlCommand cmd = new SqlCommand(sql.ToString(), connection))
46 {
47 try
48 {
49 connection.Open();
50 int rows = cmd.ExecuteNonQuery();
51 //return rows;
52 }
53 catch (System.Data.SqlClient.SqlException e)
54 {
55 connection.Close();
56 throw e;
57 }
58 finally
59 {
60 if (connection.State != ConnectionState.Closed)
61 {
62 connection.Close();
63 connection.Dispose();
64 }
65 }
66 }
67 }
68 catch (Exception ex)
69 {
70 try
71 {
72 //如果数据库记录失败,那么写入文件中
73 //throw new Exception(ex.Message);
74 //System.IO.File.WriteAllText(
75 }
76 catch (Exception ex2)
77 {
78 throw new Exception(ex2.Message);
79 }
80 }
81 }
82 }
83
84 ///
85 /// 默认构造函数
86 ///

87 public CoreException()
88 : base()
89 {
90 new CoreException(new Exception());
91 }
92
93
94 ///
95 /// 记录异常,默认不通知管理员
96 ///

97 ///
98 public CoreException(Exception ex)
99 {
100 new CoreException(ex, false);
101 }
102
103 ///
104 /// 记录异常,确定程序是否通知管理员
105 ///

106 ///
107 /// 是否需要通知管理员
108 public CoreException(Exception ex, bool alert)
109 {
110 base.Model = new ExceptionLogModel();
111
112 base.Model.ExceptionType = ex.GetType().ToString();
113 base.Model.ExceptionDescription = "错误描述 :" + ex.Message;
114 base.Model.ExceptionUser = ex.Source;
115 base.Model.ExceptionLogTime = DateTime.Now;
116 base.Model.EnabledAlert = alert;
117
118 Insert();
119 }
120
121 ///
122 /// 记录异常,不通知管理员
123 ///

124 ///
125 ///
126 public CoreException(Exception ex, object pageobj)
127 {
128 new CoreException(ex, pageobj, false);
129 }
130
131 ///
132 /// 记录异常
133 ///

134 ///
135 ///
136 ///
137 public CoreException(Exception ex, object pageobj, bool alert)
138 {
139 base.Model = new ExceptionLogModel();
140
141 base.Model.ExceptionType = ex.GetType().ToString();
142 base.Model.ExceptionDescription = "错误描述 :" + ex.Message;
143 base.Model.ExceptionUser = pageobj.GetType().ToString();
144 base.Model.ExceptionLogTime = DateTime.Now;
145 base.Model.EnabledAlert = alert;
146
147 Insert();
148 }
149
150 ///
151 /// 删除所有日志
152 ///

153 public override void Delete()
154 {
155 using (SqlConnection connection = new SqlConnection(ConnectionString))
156 {
157 string SQLStr ="DELETE FROM tbExceptionLog";
158
159 using (SqlCommand cmd = new SqlCommand(SQLStr, connection))
160 {
161 try
162 {
163 connection.Open();
164 int rows = cmd.ExecuteNonQuery();
165 //return rows;
166 }
167 catch (System.Data.SqlClient.SqlException e)
168 {
169 connection.Close();
170 throw e;
171 }
172 finally
173 {
174 if (connection.State != ConnectionState.Closed)
175 {
176 connection.Close();
177 connection.Dispose();
178 }
179 }
180 }
181 }
182 }
183
184 ///
185 /// 删除一条日志,传入参数ID
186 ///

187 ///
188 public override void Delete(int id)
189 {
190 using (SqlConnection connection = new SqlConnection(ConnectionString))
191 {
192 string SQLStr = "DELETE FROM tbExceptionLog WHERE ID=" + id.ToString();
193
194 using (SqlCommand cmd = new SqlCommand(SQLStr, connection))
195 {
196 try
197 {
198 connection.Open();
199 int rows = cmd.ExecuteNonQuery();
200 //return rows;
201 }
202 catch (System.Data.SqlClient.SqlException e)
203 {
204 connection.Close();
205 throw e;
206 }
207 finally
208 {
209 if (connection.State != ConnectionState.Closed)
210 {
211 connection.Close();
212 connection.Dispose();
213 }
214 }
215 }
216 }
217 }
218
219 ///
220 /// 批量删除
221 ///

222 ///
223 public override void Delete(string idlist)
224 {
225 using (SqlConnection connection = new SqlConnection(ConnectionString))
226 {
227 string SQLStr = "DELETE FROM tbExceptionLog WHERE ID in(" + idlist.Trim() + ")";
228
229 using (SqlCommand cmd = new SqlCommand(SQLStr, connection))
230 {
231 try
232 {
233 connection.Open();
234 int rows = cmd.ExecuteNonQuery();
235 //return rows;
236 }
237 catch (System.Data.SqlClient.SqlException e)
238 {
239 connection.Close();
240 throw e;
241 }
242 finally
243 {
244 if (connection.State != ConnectionState.Closed)
245 {
246 connection.Close();
247 connection.Dispose();
248 }
249 }
250 }
251 }
252 }
253
254 ///
255 /// 取得所有的日志记录
256 ///

257 ///
258 public override System.Data.DataSet getItems()
259 {
260 using (SqlConnection connection = new SqlConnection(ConnectionString))
261 {
262 DataSet ds = new DataSet();
263 string SQLStr ="Select * from tbExceptionLog";
264 try
265 {
266 connection.Open();
267 SqlDataAdapter command = new SqlDataAdapter(SQLStr, connection);
268 command.Fill(ds, "ds");
269 }
270 catch (System.Data.SqlClient.SqlException ex)
271 {
272 throw new Exception(ex.Message);
273 }
274 finally
275 {
276 if (connection.State != ConnectionState.Closed)
277 {
278 connection.Close();
279 connection.Dispose();
280 }
281 }
282
283 if (ds == null || ds.Tables[0].Rows.Count == 0)
284 {
285 return null;
286 }
287 else
288 {
289 return ds;
290 }
291
292 }
293 }
294
295
296 ///
297 /// 根据ID显示一条日志
298 ///

299 ///
300 public override ExceptionLogModel getItem(int id)
301 {
302 using (SqlConnection connection = new SqlConnection(ConnectionString))
303 {
304 DataSet ds = new DataSet();
305 string SQLStr = "Select * from tbExceptionLog WHERE ID=" + id.ToString();
306 try
307 {
308 connection.Open();
309 SqlDataAdapter command = new SqlDataAdapter(SQLStr, connection);
310 command.Fill(ds, "ds");
311 }
312 catch (System.Data.SqlClient.SqlException ex)
313 {
314 throw new Exception(ex.Message);
315 }
316 finally
317 {
318 if (connection.State != ConnectionState.Closed)
319 {
320 connection.Close();
321 connection.Dispose();
322 }
323 }
324
325 if (ds == null || ds.Tables[0].Rows.Count == 0)
326 {
327 return null;
328 }
329 else
330 {
331 base.Model = new ExceptionLogModel();
332 base.Model.ID = Convert.ToInt32(ds.Tables[0].Rows[0]["ID"]);
333 base.Model.ExceptionDescription = Convert.ToString(ds.Tables[0].Rows[0]["ExceptionDescription"]);
334 base.Model.ExceptionType = Convert.ToString(ds.Tables[0].Rows[0]["ExceptionType"]);
335 base.Model.ExceptionUser = Convert.ToString(ds.Tables[0].Rows[0]["ExceptionUser"]);
336 base.Model.ExceptionLogTime = Convert.ToDateTime(ds.Tables[0].Rows[0]["ExceptionLogTime"]);
337 base.Model.EnabledAlert = Convert.ToBoolean(ds.Tables[0].Rows[0]["EnabledAlert"]);
338 return (ExceptionLogModel)base.Model;
339 }
340
341 }
342 }
343
344
345 ///
346 /// 重载System.Object.ToString()方法,返回自定义信息
347 ///

348 /// 返回自定以错误信息
349 public override string ToString()
350 {
351 string a = string.Empty;
352 a = string.Format("错误信息:" + base.Model.ExceptionDescription + "错误位置:" + base.Model.ExceptionUser + "!发生时间:" + DateTime.Now.ToString() + "");
353 return a;
354 }
355
356 }
357 }

四、到这里我们剩下的就是调用了。

后话:想要实现自动发邮件,请前往【.NET开发手记】设置数据库触发器。

 1             try
2 {
3 int i = 1;
4 int j = 1 / --i;
5 }
6 catch(Exception ex)
7 {
8 //这里的ex就是捕捉到的异常
9 //如果在页面后台用的话,从sender里面取得发生异常的页面
10 //如果在其他地方,完全可以用
11 // new CoreException(ex, true);
12 //如果为true则,设置数据库AlertAdmin=1;即,通知管理员!触发触发器发邮件,默认为false,只记录不发送
13 new CoreException(ex, sender, true);
14 }

好了,就这样了,咱们看看,数据库中的数据,

自定义捕捉异常并记录到数据库模块【CoreException】_第2张图片

怎么样,清晰吧,下面是这个项目的源代码

点击下载源代码

个人网站:http://www.mrhuo.com(正在改版中)

版权所有,转载请注明出处,但代码随意使用。

转载于:https://www.cnblogs.com/MrHuo/archive/2011/09/23/2186007.html

你可能感兴趣的:(自定义捕捉异常并记录到数据库模块【CoreException】)