【问题标题】:How to catch configuration binding exception?如何捕获配置绑定异常?
【发布时间】: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


    【解决方案1】:

    通过急切地从配置中获取/绑定所需的对象并捕获启动期间引发的任何异常来提前失败。

    参考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);
    }
    
    //...
    

    请注意,通过上面的示例,可以将类显式注入依赖项,而不必包装在IOptions&lt;T&gt;, which has its own design implications

    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);    
    
    //...
    

    它应该很容易指出抛出异常的位置和原因。

    【讨论】:

    • 非常感谢,这行得通。我创建了构建配置、验证配置并在 serviceCollection 中注册的 ConfigureationProvider。如果在这个过程中出现问题,它会抛出 WrongConfigurationException。
    猜你喜欢
    • 1970-01-01
    • 2015-01-07
    • 2018-06-28
    • 1970-01-01
    • 1970-01-01
    • 2012-04-11
    • 1970-01-01
    • 1970-01-01
    • 2016-10-17
    相关资源
    最近更新 更多