设置自定义Exception的消息而不将其传递给基本构造函数 [英] Setting the message of a custom Exception without passing it to the base constructor
问题描述
我想在C#中创建一个自定义的Exception,但是从理论上讲,我确实需要先进行一些解析,然后才能制作出人类可读的ExceptionMessage.
I want to make a custom Exception in C#, but in theory I do need to do a little parsing first before I can make a human readable ExceptionMessage.
问题在于原始消息只能通过调用Messsage
的基本构造函数来设置,因此我无法提前进行任何解析.
The problem is that the orginal Message can only be set by calling the base constructor of Messsage
, so I can't do any parsing in advance.
我试图像这样覆盖Message属性:
I tried overring the Message property like this:
public class CustomException : Exception
{
string _Message;
public CustomException(dynamic json) : base("Plep")
{
// Some parsing to create a human readable message (simplified)
_Message = json.message;
}
public override string Message
{
get { return _Message; }
}
}
问题在于,在这种情况下,Visual Studio调试器仍显示我已传递给构造函数 Plep 的消息.
The problem is that the Visual Studio debugger still shows the message that I've passed into the constructor, Plep in this case.
throw new CustomException( new { message="Show this message" } )
导致:
如果我将基本构造函数留空,它将显示一条非常通用的消息:
If I leave the base constructor empty it will show a very generic message:
App.exe中发生了'App.CustomException'类型的未处理异常
问题
看起来异常对话框"读取了我也没有任何访问权限的某些字段/属性.还有其他方法可以在Exception的基本构造函数之外设置人类可读的错误消息.
It looks like the Exception Dialog reads some field/property that I don't have any access too. Is there any other way to set a human readable error message outside the base constructor on Exception.
请注意,我正在使用Visual Studio 2012.
Note that I'm using Visual Studio 2012.
推荐答案
是否只需将格式代码放入静态方法中?
Just put the formatting code into a static method?
public CustomException(dynamic json) : base(HumanReadable(json)) {}
private static string HumanReadable(dynamic json) {
return whatever you need to;
}
这篇关于设置自定义Exception的消息而不将其传递给基本构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!