public partial class App : Application
{
/// <summary>
/// 异常处理
/// </summary>
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
//捕获程序中未处理的异常(UI线程)
Application.Current.DispatcherUnhandledException += App_DispatcherUnhandledException;
//Task线程内未捕获异常处理事件
TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;
// 捕获程序中未处理的异常(非UI线程异常)
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
}
/// <summary>
/// 捕获程序中未处理的异常(UI线程)
/// </summary>
private void App_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
{
Exception ex = e.Exception;
if (ex.Message.Contains("因此无法排序数据集合"))
{
MessageBox.Show("您对\"序号\"等非数据列进行了无意义的排序!");
e.Handled = true;
return;
};
string str = ex.StackTrace;
//Log4NetHelper.WriteError(typeof(Exception), "UI线程异常;异常位置:" + str.Substring(str.LastIndexOf("\\") + 1, str.Length - str.LastIndexOf("\\") - 1) + ";异常信息:" + ex.Message);
e.Handled = true;
MessageBox.Show("软件异常报错:"+ ex.Message,"软件未处理异常");
}
/// <summary>
/// Task线程内未捕获异常处理事件
/// </summary>
private void TaskScheduler_UnobservedTaskException(object? sender, UnobservedTaskExceptionEventArgs e)
{
Exception ex = e.Exception;
string str = ex.StackTrace;
//Log4NetHelper.WriteError(typeof(Exception), "Task线程里异常;异常位置:" + str.Substring(str.LastIndexOf("\\") + 1, str.Length - str.LastIndexOf("\\") - 1) + ";异常信息:" + ex.Message);
}
/// <summary>
/// 捕获程序中未处理的异常(非UI线程异常)
/// </summary>
private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
Exception ex = e.ExceptionObject as Exception;
string str = ex.StackTrace;
//Log4NetHelper.WriteError(typeof(Exception), "非UI线程异常;异常位置:" + str.Substring(str.LastIndexOf("\\") + 1, str.Length - str.LastIndexOf("\\") - 1) + ";异常信息:" + ex.Message);
MessageBox.Show("软件致命报错:" + ex.Message, "软件致命异常");
}
}