我想在 C# 中创建自定义异常,但理论上我确实需要先进行一些解析,然后才能创建人类可读的异常消息。
问题是原来的Message只能通过调用Messsage
的基类构造函数来设置,所以无法提前解析。
我试过像这样覆盖 Message 属性:
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。
throw new CustomException( new { message="Show this message" } )
结果:
如果我将基本构造函数留空,它将显示一条非常通用的消息:
App.exe 中出现类型为“App.CustomException”的未处理异常
问题
看起来异常对话框读取了一些我也没有任何访问权限的字段/属性。是否有任何其他方法可以在异常的基本构造函数之外设置人类可读的错误消息。
请注意,我使用的是 Visual Studio 2012。
最佳答案
只是将格式化代码放到一个静态方法中?
public CustomException(dynamic json) : base(HumanReadable(json)) {}
private static string HumanReadable(dynamic json) {
return whatever you need to;
}
关于c# - 设置自定义异常的消息而不将其传递给基本构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17695482/