Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

InvalidOperationException is thrown because it fails to convert a value from appsettings.json to an enum

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{
  "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
}

>Solution :

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))
{
    ...
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading