gpt4 book ai didi

c# - Newtonsoft JObject.Parse 抛出基本异常...如何处理

转载 作者:行者123 更新时间:2023-11-30 21:58:48 25 4
gpt4 key购买 nike

使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com