c# - 如何捕获配置绑定(bind)异常?

标签 c# .net exception .net-core configuration

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

我添加了这样的强类型配置:

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

services.Configure<AppConfiguration>(configuration);

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

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)

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

最佳答案

通过急切地从配置中获取/绑定(bind)所需的对象并捕获启动期间抛出的任何异常来尽早失败。

引用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);
}

//...

请注意,在上面的示例中,可以将类显式注入(inject)到依赖项中,而不必将其包装在 IOptions<T> , 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);    

//...

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

关于c# - 如何捕获配置绑定(bind)异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56974195/

相关文章:

.net - Azure 数据工厂中 webhook 的实现

c# - 如何在linq中比较两组数据并返回公共(public)数据?

c# - 与 WCF 服务共享事件

c# - 如何在C#中获取外部IP的mac地址

c# - 如何通过属性控制方法行为?

同一 .NET 应用程序中的 C# 和 C++ 代码?

javascript - 未捕获的类型错误 : Cannot read property 'prototype' of null using Openerp 7. 0

exception - 控制或曾经与最后一团糟?

java - Camel捕获在karaf上运行的jdbc异常ClassNotFound

c# - 创建一组文件的打包二进制表示?