WPF-全局逻辑未处理异常的异常处理
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, "软件致命异常");
}
}
本文来自博客园,作者:꧁执笔小白꧂,转载请注明原文链接:https://www.cnblogs.com/qq2806933146xiaobai/p/16832285.html
分类:
.Net-WPF
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· 一文读懂知识蒸馏
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
2021-10-27 inter jion与WITH (NOLOCK) 排他锁(脏读)