c# - 如何在控制台应用程序中捕获未处理的异常
问题描述
我经常在我的控制台应用程序中发现未处理的异常。然后它会挂起并停止所有进程。在程序正常工作之前,我还被迫重新启动程序。
未处理的异常:
我的程序是一个服务器程序。我不希望它停止工作,因为它会影响业务。
我该如何处理这个错误?
解决方案
在 main 方法中注册一个全局异常处理程序,如下所示:
//Add handler to handle the exception raised by additional threads
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
然后处理方法中所有未处理的异常CurrentDomain_UnhandledException
。
private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
//Your logic here, for ex., log the exception somewhere
}
推荐阅读
- docker - 将 Envoy 设置为 Docker 容器内的反向代理
- ios - 使用笔记本电脑 react-native 在连接的 OS 设备上打开 DevMenu
- bash - 为什么 curl 不下载图片?
- angular - Angular 的 HttpClient 可以遵守 Content-Disposition 并允许保存文件吗?
- apache-kafka - 默认端口 8083 上的 Kafka Mirror Maker 2 的 REST API 调用未连接
- apache-kafka - Kafka 段被删除太频繁或根本不删除
- flutter - 有什么方法可以使用颤振的 webapp 在我自己的网站上保存数据?
- javascript - 加入购物车前如何计算产品总价?
- flutter - 如何解决 Android Studio 中的错误 24140?
- shopify - 有没有办法在 Shopify 商店中翻译块内容?