Json.NET DeserializeObject允许构造函数异常冒泡

时间:2016-08-20 18:20:02

标签: c# exception-handling json.net event-bubbling

我正在使用JsonConvert.DeserializeObject<T>(string value)方法从T反序列化string类型的对象。

在自定义类(我试图反序列化)中,我对提供给构造函数的参数执行检查,并可以抛出ArgumentNullException。但是,此异常不会通过反序列化器和原始调用者冒泡,因此异常在构造函数内保持未处理状态。

这是我在辅助类中使用的通用方法:

public static T FromJsonString<T>(string json)
{
    try
    {
        return JsonConvert.DeserializeObject<T>(json);
    }
    catch(ArgumentNullException)
    {
        // Would like to handle exception here, but never reached
    }
}

我的类构造函数示例:

[JsonConstructor]
public Profile(string name, ...)
{
    if (string.IsNullOrWhiteSpace(name)) { throw new ArgumentNullException("name"); }
    // ...
}

我在调用JsonSerializerSettings时尝试使用DeserializeObject<T>(),例如Error属性,但这没有任何区别。

如何让异常冒泡,而不是留在我班级的构造函数中?

1 个答案:

答案 0 :(得分:0)

问题是由Visual Studio打破异常引起的,因为它被归类为&#34;用户未处理&#34;。在Debug&gt;中Windows&gt;例外设置您可以更改哪些异常中断,哪些异常中断。