c#自定义异常捕获机制,让程序漏洞无处可遁
作者:admin 发布于:2014-5-31 12:13 Saturday 分类:网络转载
public class CustomExceptionHandler { public CustomExceptionHandler() { Application.ThreadException += new ThreadExceptionEventHandler(this.OnThreadException); } private void OnThreadException(object sender, ThreadExceptionEventArgs args) { try { string errorMsg = "程序运行过程中发生错误,错误信息如下:\n"; errorMsg += args.Exception.Message; errorMsg += "\n发生错误的程序集为:"; errorMsg += args.Exception.Source; errorMsg += "\n发生错误的具体位置为:\n"; errorMsg += args.Exception.StackTrace; writeLog(errorMsg); XtraMessageBox.Show("系统运行时发生未知错误!请重新启动系统", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error); Application.Exit(); } catch(Exception ex) { writeLog(ex.Message.ToString()); XtraMessageBox.Show("系统运行时发生未知错误!请重新启动系统", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error); Application.Exit(); } } /// <summary> /// 写文件 /// </summary> /// <param name="str"></param> static void writeLog(string str) { if (!Directory.Exists("ErrLog")) { Directory.CreateDirectory("ErrLog"); } using (StreamWriter sw = new StreamWriter(@"ErrLog\ErrLog.txt", true)) { sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); sw.WriteLine(str); sw.WriteLine("------------------------------------------------------------------------------------"); sw.Close(); } } }