如何捕获配置绑定异常? [英] How to catch configuration binding exception?

查看:21
本文介绍了如何捕获配置绑定异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 .NET Core 2.2 中构建控制台应用程序.

I am building a console application in .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);

我的配置绑定到 AppConfiguration 类的对象.我想知道,如何捕获在将配置值绑定到我的类时可能发生的异常?例如,我的配置属性之一是枚举.如果用户提供不存在的参数,我会收到堆栈跟踪异常:

My configuration is bound to an object of class 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:

在 System.Enum.TryParseEnum(Type enumType, String value, BooleanignoreCase、EnumResult&parseResult) 在 System.Enum.Parse(TypeenumType、字符串值、布尔值 ignoreCase) 在System.ComponentModel.EnumConverter.ConvertFrom(ITypeDescriptorContext上下文、CultureInfo 文化、对象值)

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)

基本上,我需要某种方式来知道异常是由于配置错误而不是其他问题而发生的.如果我能够捕获任何与配置绑定相关的异常,我可以抛出自己的 WrongConfigurationException 来捕获它并确保配置有问题.

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.

推荐答案

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

Fail early by eagerly getting/binding the desired object from configuration and catching any exceptions thrown during startup.

参考 绑定到对象图

//...

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,它有自己的设计含义

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

try-catch 也可以通过让它在那个点失败来放弃.

The try-catch can also be foregone by just letting it fail at that point.

//...

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.

这篇关于如何捕获配置绑定异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆