Suppose I have the following class definition
public class Person
{
[JsonProperty(Required = Required.Always)]
public string Name { get; set; }
}
And when I try to instantiate a new Person from the following text: "{}", I will get an exception
try
{
JsonConvert.DeserializeObject<Person>("{}");
}
catch(Exception ex)
{
// ex.Message = 'Required property 'Name' not found in JSON. Path '', line 1, position 2.'
}
How can I customize this error message? I have several classes with several properties per class and I'd like to simplify these errors to send back to the client. Something like
Unable to create person, 'Name' is required.
I wish not to send internal JSON exceptions to the client. I also tried a custom JsonConverter
public class Person
{
[JsonProperty(Required = Required.Always)]
[JsonConverter(typeof(MyCustomConverter))]
public string Name { get; set; }
}
but the custom converter's methods like ReadJson is not even being called when the property does not exist. Note that in the exact application I am not calling JsonConvert.DeserializeObject myself, it is automatically done in my Api endpoints so solutions like
try
{
JsonConvert.DeserializeObject<Person>(input);
}
catch(JsonException jex)
{
throw new JsonException("My custom message")
}
are really not helpful. It also does not scale to every single other property in all other classes.
You can use original exception as
InnerException. In order to do that you need to useException's constructor overload with message and inner exception:This way you will keep all relevant information about exception in
InnerException, while being able to define customized exception message.Also, if you want to use
JsonException, it also has the same constructor overload.You could also specify you custom exception class for that purpose.