【发布时间】:2011-06-02 15:17:57
【问题描述】:
我想知道是否有一种合理的方法可以自定义 .NET 框架引发的异常消息?下面是我经常写的一段代码,在很多不同的场景中,以达到为我的用户提供合理的异常信息的效果。
public string GetMetadata(string metaDataKey)
{
// As you can see, I am doing what the dictionary itself will normally do, but my exception message has some context, and is therefore more descriptive of the actual problem.
if (!_Metadata.ContainsKey(metaDataKey))
{
throw new KeyNotFoundException(string.Format("There is no metadata that contains the key '{0}'!", metaDataKey));
}
// This will throw a 'KeyNotFoundException' in normal cases, which I want, but the message "The key is not present in the dictionary" is not very informative. This is the exception who's message I wish to alter.
string val = _Metadata[metaDataKey].TrimEnd();
return val;
}
如您所见,我实际上是在生成重复的代码,只是为了使用不同的(更好的)消息。
编辑:
我正在寻找的,基本上是这样的:
KeyNotFoundException.SetMessage("this is my custom message!")
{
// OK, now this will send off the message I want when the exception appears!
// Now I can avoid all of that silly boilerplate!
string val = _Metadata[metaDataKey].TrimEnd();
}
无论如何,我认为不存在这样的功能,但如果存在,我确实会非常高兴。以前有没有人解决过这类问题?看起来我最终需要某种类型的扩展方法......
【问题讨论】:
标签: c# .net exception exception-handling customization