一、在Winform程序中捕获全局异常
在winfrom中我们需要了解Application对象中的两个事件
①Application.ThreadException 事件--当UI线程中某个异常未被捕获时出现。
②AppDomain.UnhandledException 事件--当非UI线程中某个异常未被捕获时出现。
我们需要在Program.cs中设置异常的捕捉代码(如下图所示)。
需要在Program.cs中添加的代码如下所示
static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
try
{
//设置应用程序处理异常方式:ThreadException处理
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
//处理UI线程异常
Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
//处理非UI线程异常
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
#region 应用程序的主入口点
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
#endregion
}
catch (Exception ex)
{
string str = GetExceptionMsg(ex, string.Empty);
MessageBox.Show(str, "系统错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
{
string str = GetExceptionMsg(e.Exception, e.ToString());
MessageBox.Show(str, "系统错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
//LogManager.WriteLog(str);
}
static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
string str = GetExceptionMsg(e.ExceptionObject as Exception, e.ToString());
MessageBox.Show(str, "系统错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
//LogManager.WriteLog(str);
}
/// <summary>
/// 生成自定义异常消息
/// </summary>
/// <param name="ex">异常对象</param>
/// <param name="backStr">备用异常消息:当ex为null时有效</param>
/// <returns>异常字符串文本</returns>
static string GetExceptionMsg(Exception ex, string backStr)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("****************************异常文本****************************");
sb.AppendLine("【出现时间】:" + DateTime.Now.ToString());
if (ex != null)
{
sb.AppendLine("【异常类型】:" + ex.GetType().Name);
sb.AppendLine("【异常信息】:" + ex.Message);
sb.AppendLine("【堆栈调用】:" + ex.StackTrace);
}
else
{
sb.AppendLine("【未处理异常】:" + backStr);
}
sb.AppendLine("***************************************************************");
return sb.ToString();
}
}
二、在Web中捕获全局异常
我们只需要在Global.asax文件中添加异常捕获的代码即可。
Global.asax代码
public class Global : System.Web.HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
// 在应用程序启动时运行的代码
}
protected void Session_Start(object sender, EventArgs e)
{
// 在新会话启动时运行的代码
}
protected void Application_BeginRequest(object sender, EventArgs e)
{
}
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
}
protected void Application_Error(object sender, EventArgs e)
{
// 在出现未处理的错误时运行的代码
Exception objExp = HttpContext.Current.Server.GetLastError();
Class2.ErrorLog("<br/><strong>客户机IP</strong>:" + Request.UserHostAddress + "<br /><strong>错误地址</strong>:" + Request.Url, objExp);
}
protected void Session_End(object sender, EventArgs e)
{
// 在会话结束时运行的代码。
// 注意: 只有在 Web.config 文件中的 sessionstate 模式设置为
// InProc 时,才会引发 Session_End 事件。如果会话模式设置为 StateServer
// 或 SQLServer,则不会引发该事件。
}
protected void Application_End(object sender, EventArgs e)
{
// 在应用程序关闭时运行的代码
}
}
Class2.ErrorLog方法
public static void ErrorLog(string info, Exception ex)
{
if (!string.IsNullOrEmpty(info) && ex != null)
{
string errorMsg = string.Format("【异常类型】:{0} <br>【异常信息】:{1} <br>【堆栈调用】:{2}", new object[] { ex.GetType().Name, ex.Message, ex.StackTrace });
}
}