Skip to content

Deserialization of unknown enum value #277

@HaydnDias

Description

@HaydnDias

Hello!

Whilst testing we found a regression after switching from nswag -> kiota, we used to get a Newtonsoft.Json.JsonSerializationException when we deserialized an entity with an unknown enum value, it'd give us an error like Error converting value "EXAMPLE_ENUM_STRING_VALUE" to type 'System.Nullable`1[Example.Project.Models.ExampleEnum]'..

With kiota, the JsonParseNode returns null if it can't parse it, I know we can implement our own IParseNode and IParseNodeFactory for this, however it does seem wastefulhaving to have a copy of the entire JsonParseNode class for what is effectively a one line change, and it means that we'll need to keep our implementation up to date with changes made here if we want to keep it as close to the default implementation as possible.

Currently we've made a change to GetEnumValue as below:

{
	var rawValue = _jsonNode.GetString();
	if(string.IsNullOrEmpty(rawValue)) return null;
	
	var type = typeof(T);
	rawValue = ToEnumRawName<T>(rawValue!);
	if(type.GetCustomAttributes<FlagsAttribute>().Any())
	{
		return (T)(object)rawValue!
			.Split(',')
			.Select(x => Enum.TryParse<T>(x, true, out var result) ? result : (T?)null)
			.Where(x => !x.Equals(null))
			.Select(x => (int)(object)x!)
			.Sum();
	}
	else
-		return Enum.TryParse<T>(rawValue, true,out var result) ? result : null;
+		return Enum.TryParse<T>(rawValue, true,out var result) ? result : 
+				throw new ArgumentOutOfRangeException(type.FullName, rawValue, "Unable to parse enum value");
}

Reasoning for this is we'd like to catch and log when we receive a new enum value as sometimes third parties do add new ones without telling us and we need to be aware.

What are your thoughts on potential solutions to adding something official to be able to handle cases like this?

Metadata

Metadata

Assignees

No one assigned

    Labels

    area:serializationFocused on functional modules of the product

    Type

    No type

    Projects

    Status

    New📃

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions