I want to change the ResponseBody when a request fails because deserialization to an Enum wasn't successful. The application is a .NET Core 3 API.
I've got the following property on one of my entities:
[JsonConverter(typeof(StringEnumConverter))]
public Attribute Attribute { get; set; }
where Attribute is the following Enum:
public enum Attribute
{
[EnumMember(Value = "value-1")]
value1,
[EnumMember(Value = "value-2")]
value2,
[EnumMember(Value = "some-value")]
somevalue
}
When I try to POST a body with a wrong value for the Enum:
{
"attribute": "wrong-value"
}
My endpoint returns a 400 with a Newtonsoft error and I'd like to return a ResponseBody created by me instead.
{
"errors": {
"attribute": [
"Error converting value \"wrong-value\" to type 'Project.Attribute'. Path 'attribute', line 10, position 24."
]
},
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "|1cf19d18-4577510ef4de1g923."
}
Is there a way to intercept such error with a middleware and return a custom ResponseBody?