【发布时间】: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<T>() 时使用JsonSerializerSettings,例如Error 属性,但这没有任何区别。
我怎样才能让异常冒泡而不留在我的类的构造函数中?
【问题讨论】:
-
为什么不使用像 if (json.isNullOrWhitespace) throw new argumentNullException() 这样的简单保护子句?
-
你确定不是VS调试异常设置问题?我已经尝试过这样的事情,但例外是像往常一样“冒泡”。
-
@IvanStoev 我现在检查调试异常设置
-
@PaoloMontgomeryRusso 这是不可能的,因为整个json字符串可能有内容,但里面的信息不符合构造函数检查,因此必须在构造函数内部检查
-
@IvanStoev 你说得对,是VS调试设置问题,自动设置为break因为没有立即处理,谢谢!
标签: c# exception-handling json.net event-bubbling