Hello, so long story short I have a web app, which uses Json deserialization in order to display information about products:
var ProductInfo = JsonConvert.DeserializeObject<Product>(Product.CertificateFieldsHeader);
I want to avoid situation in which if deserialization fails (for example JSON is invalid), user will get a 500 error.
What I have tried:
First thing which came to my mind was simply throwing it into try catch block:
try
{
var ProductInfo = JsonConvert.DeserializeObject<Product>(Product.CertificateFieldsHeader);
}
catch (JsonException jsonException)
{
_logger.LogInformation(jsonException);
}
...but that solution didn't seem to be very elegant.
I have also thought about creating an extension method, for example:
public static bool TryParseJson<T>(this string obj, out T result)
{
try
{
JsonSerializerSettings settings = new JsonSerializerSettings();
settings.MissingMemberHandling = MissingMemberHandling.Error;
result = JsonConvert.DeserializeObject<T>(obj, settings);
return true;
}
catch (Exception)
{
result = default(T);
return false;
}
}
But that method wasn't catching any errors when I tested it. How should I approach the problem? Just stick to simple try catch block?