简体   繁体   English

如何捕获配置绑定异常?

[英]How to catch configuration binding exception?

I am building a console application in .NET Core 2.2.我正在 .NET Core 2.2 中构建一个控制台应用程序。

I added strongly-typed configuration like this:我添加了这样的强类型配置:

var configuration = new ConfigurationBuilder()
    .SetBasePath(Directory.GetCurrentDirectory())
    .AddJsonFile("appsettings.json", true)
    .AddCommandLine(args)
    .Build();

services.Configure<AppConfiguration>(configuration);

My configuration is bound to an object of class AppConfiguration .我的配置绑定到类AppConfiguration的对象。 I wonder, how can I catch exceptions that could happen while binding config values to my class?我想知道,如何捕获在将配置值绑定到我的类时可能发生的异常? For example, one of my configuration properties is an enum.例如,我的配置属性之一是枚举。 If user provides nonexisting parameter, I get exception with stack trace:如果用户提供不存在的参数,我会收到堆栈跟踪异常:

at System.Enum.TryParseEnum(Type enumType, String value, Boolean ignoreCase, EnumResult& parseResult) at System.Enum.Parse(Type enumType, String value, Boolean ignoreCase) at System.ComponentModel.EnumConverter.ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, Object value)在 System.Enum.TryParseEnum(Type enumType, String value, Boolean ignoreCase, EnumResult& parseResult) at System.Enum.Parse(Type enumType, String value, Boolean ignoreCase) at System.ComponentModel.EnumConverter.ConvertFrom(ITypeDescriptorContext context, CultureInfo culture,对象值)

Basically, I need some way to know that exception happened because of wrong configuration and not some other problem.基本上,我需要某种方式来知道异常是由于配置错误而不是其他问题而发生的。 If I was able to catch any configuration binding-related exceptions, I could throw my own WrongConfigurationException to catch it and be sure that something was wrong with config.如果我能够捕获任何与配置绑定相关的异常,我可以抛出我自己的 WrongConfigurationException 来捕获它并确保 config 出现问题。

Fail early by eagerly getting/binding the desired object from configuration and catching any exceptions thrown during startup.通过急切地从配置中获取/绑定所需的对象并捕获启动期间抛出的任何异常来尽早失败。

Reference Bind to an object graph引用绑定到对象图

//...

var configuration = new ConfigurationBuilder()
    .SetBasePath(Directory.GetCurrentDirectory())
    .AddJsonFile("appsettings.json", true)
    .AddCommandLine(args)
    .Build();

try {
    //bind to object graph
    AppConfiguration appConfig = configuration.Get<AppConfiguration>();

    //custom validation can be done here as well
    //...        

    //if valid add to service collection.
    services.AddSingleton(appConfig);    
} catch(Exception ex) {
    throw new WrongConfigurationException("my message here", ex);
}

//...

Note that with the above example the class can be explicitly injected into dependents without having to be wrapped in IOptions<T> , which has its own design implications请注意,在上面的示例中,可以将类显式注入到依赖项中,而不必包装在IOptions<T> ,这有其自身的设计含义

The try-catch can also be foregone by just letting it fail at that point. try-catch 也可以通过让它在那个点失败来放弃。

//...

var configuration = new ConfigurationBuilder()
    .SetBasePath(Directory.GetCurrentDirectory())
    .AddJsonFile("appsettings.json", true)
    .AddCommandLine(args)
    .Build();


//bind to object graph
AppConfiguration appConfig = configuration.Get<AppConfiguration>();

//custom validation can be done here as well
if(/*conditional appConfig*/)
    throw new WrongConfigurationException("my message here");

//if valid add to service collection.
services.AddSingleton(appConfig);    

//...

It should easily indicate where and why the exception was thrown.它应该很容易指出在哪里以及为什么抛出异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM