C#:自定义异常的覆盖toString()方法
题
我有一个自定义异常类,其中包含一些其他字段。我希望这些写在 ToString()
方法,但是如果我自己实施 ToString()
, ,我放松了其他一些有用的东西(例如编写异常类型名称,内部异常数据和堆栈跟踪)。
什么是实施自己的最佳方法/模式 ToString()
除了这种例外吗?理想情况下,它应该重复使用现有机制,但以类似于默认的方式进行格式 ToString()
执行。
更新:例如,预处或附加我的自定义字段到base.tostring()文本不是理想的恕我直言
PimTool.Utilities.OERestServiceUnavailableException: test ---> System.InvalidOperationException: inner message
--- End of inner exception stack trace ---
at PimTool.Tests.Services.OE.OERestClientTests.ExceptionsLogging() in D:\svn\NewPimTool\PimTool.Tests\Services\OE\OERestClientTests.cs:line 178,
StatusCode=0, message='test', requestId='535345'
表示自定义字段写在(可能长)异常描述的末尾。另一方面,我希望异常类型是描述中写的第一个信息。
更新2:我已经为此实施了一个解决方案,请在下面查找我自己的答案。
解决方案 3
好的,这就是我想出的。我已经实施了一个扩展类,该类复制了格式化异常的原始机制,但是有一个扭曲:一个自定义操作代表,该委托提供用于格式化自定义字段的插件:
public static class ExceptionFormatterExtensions
{
public static string ExceptionToString (
this Exception ex,
Action<StringBuilder> customFieldsFormatterAction)
{
StringBuilder description = new StringBuilder();
description.AppendFormat("{0}: {1}", ex.GetType().Name, ex.Message);
if (customFieldsFormatterAction != null)
customFieldsFormatterAction(description);
if (ex.InnerException != null)
{
description.AppendFormat(" ---> {0}", ex.InnerException);
description.AppendFormat(
"{0} --- End of inner exception stack trace ---{0}",
Environment.NewLine);
}
description.Append(ex.StackTrace);
return description.ToString();
}
}
现在,您可以在自己的tostring()实现中使用此方法,而无需重复格式代码:
public override string ToString()
{
return this.ExceptionToString(
description =>
{
description.AppendFormat(
", HttpStatusCode={0}, RequestId='{1}'",
httpStatusCode,
RequestId);
});
}
其他提示
这是全杀。您的例外应该仅覆盖消息属性。
public override String Message {
get {
return base.Message + String.Format(", HttpStatusCode={0}, RequestId='{1}'",
httpStatusCode,
RequestId);
}
}
异常类的默认tostring方法基本上是”ClassName: Message --> InnerException.ToString() StackTrace
“因此,覆盖消息将您的消息文本准确地放在应该的位置。
您可以手动将默认数据添加到由 ToString
, ,通过查看异常属性。例如,以下将模拟默认情况下返回的数据 ToString
方法(假设没有内部例外):
string.Format("{0}: {1}\r\n{2}", this.GetType().Name, this.Message, this.StackTrace);
或者,您可以简单地附加(或预处)返回的数据 base.ToString
您要添加的信息。
您可以覆盖ToString()方法以包含您自己的自定义信息,并且仍然调用默认基础异常ToString()这样:
public class MyException : Exception
{
public string CustomField { get; set; }
public override string ToString()
{
return CustomField + Environment.NewLine + base.ToString();
}
}
如果您主要在调试器中查看它们,则可以使用 [DebuggerDisplay]
属性以指定其格式,而不是触摸现有的 ToString
方法。
否则,只需超载 ToString
并确保致电基类版本 base.ToString()
在覆盖呼叫base.tostring()中,并根据您的需求修改结果字符串...