Files
NetVizor/Shell/App.xaml.cs
T
2025-05-28 21:59:56 +08:00

121 lines
3.6 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.Configuration;
using System.Data;
using System.Net.Http;
using System.Windows;
using System.Windows.Threading;
using Application.Utils;
using Common.Logger;
using Microsoft.Extensions.Logging;
namespace Shell;
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : System.Windows.Application
{
protected override void OnStartup(StartupEventArgs e)
{
// 异常处理
ExceptionCatch();
base.OnStartup(e);
// ✅ 启动你的服务(如 WebSocket、HTTP、端口监听等)
StartMyServer();
}
/// <summary>
/// 异常捕捉
/// </summary>
private void ExceptionCatch()
{
DispatcherUnhandledException += App_DispatcherUnhandledException;
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
// 注册全局异常处理
TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;
}
/// <summary>
/// 处理异常
/// </summary>
/// <param name="exception"></param>
private void HandleException(Exception? exception)
{
Log.Error("未捕获异常", exception);
// 错误记录,错误处理
if (exception != null)
{
// todo:2023年10月29日 恭喜你发现了BUG页面
MessageBox.Show($"恭喜你发现了BUG,请联系管理员解决:{exception.Message}");
}
}
private void App_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
{
Log.Error(e.Exception, "UI线程异常");
HandleException(e.Exception);
// 根据异常类型决定是否继续运行
if (CanRecover(e.Exception))
{
e.Handled = true; // 标记为已处理,防止应用崩溃
// ShowUserFriendlyMessage("操作失败,请重试");
}
else
{
// ShowCriticalErrorDialog(e.Exception);
// 让应用正常关闭而不是崩溃
}
}
private void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
{
foreach (var ex in e.Exception.InnerExceptions)
{
Log.Error(e.Exception, "UI线程异常");
}
e.SetObserved(); // 标记异常已被观察,防止应用终止
}
private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
var exception = e.ExceptionObject as Exception;
Log.Error(exception, "非UI线程异常");
if (e.IsTerminating)
{
// 应用即将终止,进行紧急清理
// EmergencyCleanup();
Log.Fatal("应用程序即将因未处理异常而终止");
}
}
private bool CanRecover(Exception exception)
{
return exception switch
{
ArgumentException => true,
InvalidOperationException => true,
HttpRequestException => true,
TimeoutException => true,
OutOfMemoryException => false,
StackOverflowException => false,
AccessViolationException => false,
_ => true
};
}
private void StartMyServer()
{
int port = SysHelper.GetAvailablePort();
Console.WriteLine($"服务启动在端口: {port}");
// 例如开启线程或任务监听 WS:
Task.Run(() =>
{
StartWebSocketServer(port);
});
}
private void StartWebSocketServer(int port)
{
// 示例服务逻辑,如上文 WebSocket 实现
}
}