Home > Blockchain >  InvalidOperationException is thrown because it fails to convert a value from appsettings.json to an
InvalidOperationException is thrown because it fails to convert a value from appsettings.json to an

Time:09-23

config.GetValue<SubscriberKind?> is throwing the following exception if Kind in appsettings.json is set to something which cannot be found in the enum. How do I fix it?

System.InvalidOperationException: Failed to convert configuration value at 'Subscriber:Kind' to type 'Subscriber.Kinds.SubscriberKind'.

How do I fix it or is there a better solution which doesn't fail in such way, I don't mind if it's not enum?

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ProtoActor": {
    "AdvertisedHost": "localhost"
  },
  "Subscriber": {
    "Exchange": "ftx",
    "Kind": "DropCopy",
  }
}

internal static class ConfiguratorFactory
{
    public static ISubscriptionConfigurator Create(IConfiguration config)
    {
        var subscriberKind = config.GetValue<SubscriberKind?>("Subscriber:Kind");

        return subscriberKind switch
        {
            SubscriberKind.UserTrades => new UserTrades.FtxConfigurator(config),
            _ => throw new ArgumentOutOfRangeException(nameof(subscriberKind))
        };
    }
}

public enum SubscriberKind
{
    UserTrades
}

CodePudding user response:

You can read value as string and then try processing it as enum:

var value = config.GetValue<string>("Subscriber:Kind");
if (Enum.TryParse(value, out SubscriberKind kind))
{
    ...
}
  • Related