设置自定义 Exception 的消息而不将其传递给基构造函数

我想在 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; }
}
}

问题是 VisualStudio 调试器仍然显示我传递给构造函数的消息,在本例中为 拜托

throw new CustomException( new { message="Show this message" } )

结果:

Visual Studio Exception Dialog

如果我让基本构造函数为空,它将显示一个非常通用的消息:

App.exe 中发生了“ App.CustomException”类型的未处理异常

提问

它看起来像异常对话框读取一些字段/属性,我没有任何访问太多。是否有其他方法在 Exception 的基构造函数之外设置人类可读的错误消息。

注意,我正在使用 VisualStudio2012。

54733 次浏览

Consider the Microsoft Guidelines for creating new exceptions:

  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);
}
}

Note the static factory method (not part of the pattern), that you can use in your program like this:

throw CustomException.FromJson(variable);

That way you followed best practice and can parse your json inside the exception class.

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;
}

I think the problem may be with the Visual Studio debugger. I got the same exact results you got using the debugger, but when I print the message instead:

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);
}
}
}

I get the expected "Show this message".

If you put a breakpoint where the Exception is caught, the debugger does show you the correct message.

I like to use this here. It is easy and does not need the static function:

public class MyException : Exception
{
public MyException () : base("This is my Custom Exception Message")
{
}
}

What's wrong with something like this.

    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)
{ }


}

I just use a string and include parameters. Simple solution.