使用 Newtonsoft Json.NET 6.0.8,我有这样的代码:
public bool ValidateSchema<T>(T model, out IList<string> messages)
{
string stringedObject = Newtonsoft.Json.JsonConvert.SerializeObject(model,
new JsonSerializerSettings()
{
ContractResolver = new CamelCasePropertyNamesContractResolver(),
NullValueHandling = NullValueHandling.Include
});
messages = new List<string>();
JObject objectToValidate;
try
{
objectToValidate = JObject.Parse(stringedObject);
}
catch (Exception)
{
messages.Add("Unable to parse jsonObject.");
return false;
}
JsonSchema schema = JsonSchemaRepository.SchemaDictionary[typeof(T)];
return objectToValidate.IsValid(schema, out messages);
}
特别是 try catch block 。从我的阅读来看,这个方法似乎只抛出我不想捕获的基本异常,因为它可能隐藏各种其他重要错误。
现在 Json.NET nuget 包非常专业,所以我不得不怀疑我是否错误地实现了我的解析方法,或者关于如何处理解析错误的任何其他想法。
也许记录并重新抛出?
TIA
最佳答案
您可以捕获基本异常,然后如果它是异常的子类,则重新抛出它。
try
{
objectToValidate = JObject.Parse(stringedObject);
}
catch (Exception e)
{
if (e.GetType().IsSubclassOf(typeof(Exception)))
throw;
//Handle the case when e is the base Exception
messages.Add("Unable to parse jsonObject.");
return false;
}
关于c# - Newtonsoft JObject.Parse 抛出基本异常...如何处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29830198/