【发布时间】:2019-11-20 06:53:22
【问题描述】:
我正在 .NET Core 2.2 中构建控制台应用程序。
我添加了这样的强类型配置:
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", true)
.AddCommandLine(args)
.Build();
services.Configure<AppConfiguration>(configuration);
我的配置绑定到AppConfiguration 类的对象。我想知道,如何在将配置值绑定到我的类时捕获可能发生的异常?例如,我的配置属性之一是枚举。如果用户提供不存在的参数,我会得到堆栈跟踪异常:
在 System.Enum.TryParseEnum(Type enumType, String value, Boolean 在 System.Enum.Parse(Type enumType,字符串值,布尔忽略大小写)在 System.ComponentModel.EnumConverter.ConvertFrom(ITypeDescriptorContext 上下文、CultureInfo 文化、对象值)
基本上,我需要一些方法来知道异常是由于错误的配置而不是其他问题而发生的。如果我能够捕获任何与配置绑定相关的异常,我可以抛出我自己的 WrongConfigurationException 来捕获它并确保配置有问题。
【问题讨论】:
标签: c# .net exception .net-core configuration