我想在C#中创建一个自定义Exception,但理论上我需要先做一点解析才能创建一个人类可读的ExceptionMessage。
问题是原始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”类型异常
问题
看起来Exception Dialog读取了一些我也没有访问权限的字段/属性。是否有任何其他方法可以在Exception上的基础构造函数外部设置人类可读的错误消息。
请注意,我正在使用Visual Studio 2012。
答案 0 :(得分:79)
只需将格式代码放入静态方法?
public CustomException(dynamic json) : base(HumanReadable(json)) {}
private static string HumanReadable(dynamic json) {
return whatever you need to;
}
答案 1 :(得分:14)
考虑用于创建新例外的Microsoft指南:
using System;
using System.Runtime.Serialization;
[Serializable]
public class CustomException : Exception
{
//
// For guidelines regarding the creation of new exception types, see
// https://msdn.microsoft.com/en-us/library/ms229064(v=vs.100).aspx
//
public CustomException()
{
}
public CustomException(string message) : base(message)
{
}
public CustomException(string message, Exception inner) : base(message, inner)
{
}
protected CustomException(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
public static CustomException FromJson(dynamic json)
{
string text = ""; // parse from json here
return new CustomException(text);
}
}
请注意您可以在程序中使用的静态工厂方法(不是模式的一部分),如下所示:
throw CustomException.FromJson(variable);
这样你就可以遵循最佳实践并在异常类中解析你的json。
答案 2 :(得分:7)
我认为问题可能出在Visual Studio调试器上。我得到了使用调试器的相同结果,但是当我打印消息时:
class CustomException : Exception {
public CustomException(dynamic json)
: base("Plep") {
_Message = json.message;
}
public override string Message {
get { return _Message; }
}
private string _Message;
}
class Program {
static void Main(string[] args) {
try {
throw new CustomException(new { message = "Show this message" });
} catch (Exception ex) {
Console.WriteLine(ex.Message);
}
}
}
我得到了预期的"Show this message"
。
如果将断点放在捕获异常的位置,调试器会显示正确的消息。
答案 3 :(得分:1)
我喜欢在这里使用它。它很简单,不需要静态功能:
public class MyException : Exception
{
public MyException () : base("This is my Custom Exception Message")
{
}
}
答案 4 :(得分:0)
像这样的事情怎么了
public class FolderNotEmptyException : Exception
{
public FolderNotEmptyException(string Path) : base($"Directory is not empty. '{Path}'.")
{ }
public FolderNotEmptyException(string Path, Exception InnerException) : base($"Directory is not empty. '{Path}'.", InnerException)
{ }
}
我只使用一个字符串并包含参数。简单的解决方案。