我有一个 C# Silverlight 应用程序,它随机抛出一个“KeyNotFoundException
“。我不知道找不到什么钥匙。这让我想到了两个问题:
- Does a
KeyNotFoundException
存储/暴露它试图找到什么密钥?当我查看文档 http://msdn.microsoft.com/en-us/library/9a35cy81.aspx,我没有看到任何暗示此信息可用的信息。
- 我在通用 Application.UnhandledException 事件处理程序中捕获/记录此异常。我的问题是,如果我在这里捕获该事件,我是否可以将 ExceptionObject 转换为 KeyNotFoundException,并且如果按照 #1 中的要求公开,仍然可以获得关键信息?
非常感谢你的帮助!
当字典抛出一个KeyNotFoundException
,它不会尝试告诉您它试图找到哪个键。因此,我通常尝试在字典上使用扩展方法,这样如果我的程序出现故障,我就知道它尝试查找哪个键。虽然了解堆栈跟踪很有帮助,但通常还不够,特别是当查找发生在循环内时。
public static TValue GetOrThrow<TKey,TValue>(this IDictionary<TKey,TValue> d, TKey key)
{
try
{
return d[key];
}
catch(KeyNotFoundException ex)
{
throw new KeyNotFoundException(key.ToString()
+ " was not found in the dictionary");
}
}
更新/澄清
我实际上并没有打电话key.ToString()
因为它可能是一种不会覆盖的类型ToString()
。默认情况下会打印类型名称:"MyLibrary.SomeType was not found."
,这没有那么有帮助"{ managerId: 123, employeeId: 456} was not found."
.
因此,我将其序列化为 json,如下所示:
var serializedKey = Newtonsoft.Json.JsonConvert.SerializeObject(
key,
new JsonSerializerSettings
{
//make it easy for humans to read
Formatting = Formatting.Indented,
//don't break on loops...that would cause a new error that hides the KeyNotFound!
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
});
此外,我发现将特定键值放入异常消息中可能会导致难以在日志中聚合异常,具体取决于您使用的工具类型。 (我正在使用一个将错误按外部异常的消息)。如果这影响到您,您可能需要将详细信息放入内部异常中:
throw new KeyNotFoundException(
"key was not found",
new KeyNotFoundException(serializedKey));
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)