AppDomain.CurrentDomain.UnhandledException在 System.CommandLine中不起作用
下面代码中故意抛出的除零错误不会被UnhandledExceptionTrapper函数处理,因为它位于System.CommandLine SetAction函数内部。
有没有人知道如何把SetAction方法中发生的未处理异常包含在内?
using System.CommandLine;
AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionTrapper;
var testCommand = new Command("test");
testCommand.SetAction(args =>
{
int x = 0;
int y = 15 / x;
});
RootCommand rootCommand = new RootCommand { testCommand };
await rootCommand.Parse(args).InvokeAsync();
static void UnhandledExceptionTrapper(object sender, UnhandledExceptionEventArgs e)
{
Console.WriteLine("Inside UnhandledExceptionTrapper");
Console.WriteLine(e.ExceptionObject.ToString());
System.Environment.Exit(1);
}
解决方案
默认情况下 System.CommandLine 将使用它自己的处理程序来处理。
你可以通过向 Invoke 或 InvokeAsync 传递一个 InvocationConfiguration 来覆盖它,同时检查 EnableDefaultExceptionHandler 是否为 false。
var parse = myRootCommand.Parse(Args);
var invokeCfg = new InvocationConfiguration {
EnableDefaultExceptionHandler = false,
ProcessTerminationTimeout = null
};
var result = await parse.InvokeAsync(invokeCfg, canTok);
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。