C# 设置自定义异常的消息而不将其传递给基本构造函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17695482/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Setting the message of a custom Exception without passing it to the base constructor
提问by Dirk Boer
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.
我想在 C# 中创建一个自定义异常,但理论上我确实需要先做一些解析,然后才能创建人类可读的 ExceptionMessage。
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.
问题是只能通过调用 的基本构造函数来设置原始消息Messsage
,因此我无法提前进行任何解析。
I tried overring the Message property like this:
我尝试像这样覆盖 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; }
}
}
The problem is that the Visual Studio debugger still shows the message that I've passed into the constructor, Plepin this case.
问题是 Visual Studio 调试器仍然显示我传递给构造函数的消息,在本例中为Plep。
throw new CustomException( new { message="Show this message" } )
results in:
结果是:
If I leave the base constructor empty it will show a very generic message:
如果我将基本构造函数留空,它将显示一条非常通用的消息:
An unhandled exception of type 'App.CustomException' occurred in App.exe
App.exe 中发生类型为“App.CustomException”的未处理异常
Question
题
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.
看起来异常对话框读取了一些我也没有任何访问权限的字段/属性。有没有其他方法可以在 Exception 上的基本构造函数之外设置人类可读的错误消息。
Note that I'm using Visual Studio 2012.
请注意,我使用的是 Visual Studio 2012。
采纳答案by Sebastian Redl
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;
}
回答by nvoigt
Consider the Microsoft Guidelines for creating new exceptions:
考虑创建新例外的 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);
}
}
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.
这样您就遵循了最佳实践,并且可以在异常类中解析您的 json。
回答by Ferruccio
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:
我认为问题可能出在 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);
}
}
}
I get the expected "Show this message"
.
我得到了预期的"Show this message"
.
If you put a breakpoint where the Exception is caught, the debugger does show you the correct message.
如果在捕获异常的位置放置断点,调试器会向您显示正确的消息。
回答by Simons0n
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")
{
}
}
回答by Kieran Foot
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.
我只使用一个字符串并包含参数。简单的解决方案。