一、背景介绍
代替在项目中各个方法里面写try catch,让代码只关注于业务处理即可。
二、具体实现
2.1 Program主程序里面添加事件
/// <summary>
/// 应用程序的主入口点.
/// </summary>
[STAThread]
private static void Main()
{
// 处理未捕获的异常
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
// 处理UI线程异常
Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
// 处理非UI线程异常
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(AppDomain_UnhandledException);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
/// <summary>
/// 是否退出应用程序.
/// </summary>
private static bool isExit = false; // 设置为否
/// <summary>
/// 处理非UI线程异常.
/// </summary>
/// <param name="sender">sender.</param>
/// <param name="e">e.</param>
private static void AppDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
string errorMessageIsTerminating = $"非UI线程异常:IsTerminating{e.IsTerminating.ToString()}";
string errorMessageExceptionObject = $"非UI线程异常:ExceptionObject{e.ExceptionObject.ToString()}";
LogHelper.SetErrorLog(errorMessageIsTerminating);
LogHelper.SetErrorLog(errorMessageExceptionObject);
while (true)
{
// 循环处理,否则应用程序将会退出
if (isExit)
{
// 如果设置了退出,则关闭程序退出
return;
}
System.Threading.Thread.Sleep(2 * 1000);
}
}
/// <summary>
/// 处理UI线程异常.
/// </summary>
/// <param name="sender">sender.</param>
/// <param name="e">e.</param>
private static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
{
string errorMessageStackTrace = $"UI线程异常:StackTrace{e.Exception.StackTrace.ToString()}";
string errorMessageExceptionMessage = $"UI线程异常:ExceptionObject{e.Exception.Message.ToString()}";
LogHelper.SetErrorLog(errorMessageStackTrace);
LogHelper.SetErrorLog(errorMessageExceptionMessage);
}
2.2 测试方法
可以去自己的任何一个service文件里面写一个错误,然后看是否抓取到,我这边设置的是出现异常时,窗体不关闭,程序还能继续运行。