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, "软件致命异常");
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
- 32.
- 33.
- 34.
- 35.
- 36.
- 37.
- 38.
- 39.
- 40.
- 41.
- 42.
- 43.
- 44.
- 45.
- 46.
- 47.
- 48.
- 49.
- 50.
- 51.
- 52.
- 53.
- 54.
作者:꧁执笔小白꧂