【问题标题】:Json.NET DeserializeObject allow constructor exception to bubble upJson.NET DeserializeObject 允许构造函数异常冒泡
【发布时间】:2016-08-20 18:20:01
【问题描述】:

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

在一个自定义类(我试图反序列化)中,我对提供给构造函数的参数进行检查,并可以抛出一个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"); }
    // ...
}

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

我怎样才能让异常冒泡而不留在我的类的构造函数中?

【问题讨论】:

  • 为什么不使用像 if (json.isNullOrWhitespace) throw new argumentNullException() 这样的简单保护子句?
  • 你确定不是VS调试异常设置问题?我已经尝试过这样的事情,但例外是像往常一样“冒泡”。
  • @IvanStoev 我现在检查调试异常设置
  • @PaoloMontgomeryRusso 这是不可能的,因为整个json字符串可能有内容,但里面的信息不符合构造函数检查,因此必须在构造函数内部检查
  • @IvanStoev 你说得对,是VS调试设置问题,自动设置为break因为没有立即处理,谢谢!

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


【解决方案1】:

该问题是由 Visual Studio 中断异常引起的,因为它被归类为“用户未处理”。在 Debug > Windows > Exception Settings 中,您可以更改哪些异常会中断,哪些不会。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多