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

标签 c# json.net

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

相关文章:

c# - 如何对异常处理程序中间件进行单元测试

c# - 分支执行后如何返回管道根?

c# - switch 语句中的多个 case

c# - 将 JObject 转换为 Dictionary<string, object>。可能吗?

c# - JsonConvert.SerializeObject : Unexpected result when Serializing null value

c# - 将 JSON 反序列化为任何对象

c# - 使用 linq C# 更新列表

c# - 在 UWP C# 中居中 RelativePanels

c# - 奇怪的 Json.net 异常 "Input string was not in a correct format."

c# - Newtonsoft.Json - 将通用对象反序列化为包装类