我有记录的代码Exception.Message.但是,我读了一篇文章,说明最好使用它Exception.ToString().使用后者,您可以保留有关错误的更重要信息.
这是真的,继续更换所有代码记录Exception.Message是否安全?
我也在为log4net使用基于XML的布局.是否Exception.ToString()可能包含无效的XML字符,这可能会导致问题?
是否有任何方法可以编写LINQ样式的"简写"代码,用于遍历抛出Exception的所有级别的InnerException?我宁愿写它而不是调用扩展函数(如下所示)或继承Exception类.
static class Extensions
{
public static string GetaAllMessages(this Exception exp)
{
string message = string.Empty;
Exception innerException = exp;
do
{
message = message + (string.IsNullOrEmpty(innerException.Message) ? string.Empty : innerException.Message);
innerException = innerException.InnerException;
}
while (innerException != null);
return message;
}
};
Run Code Online (Sandbox Code Playgroud) 记录完整异常详细信息(包括所有可能的内部异常)的最佳做法是什么?
目前,我使用以下代码:
try
{
//some code that throws an exception
}
catch(Exception ex)
{
do
{
Console.WriteLine(ex.Message+ex.StackTrace);
ex=ex.InnerException;
}while(ex!=null)
}
Run Code Online (Sandbox Code Playgroud)
是否存在此代码可能失败的情况?
是否有任何API允许打印所有与异常相关的信息(堆栈跟踪,内部等...)?就像抛出异常一样 - 所有数据都打印到标准输出 - 是否有任何专用方法可以完成所有操作?
谢谢
这是.NET的实际来源System.Exception.ToString:
public override string ToString()
{
return this.ToString(true, true);
}
private string ToString(bool needFileLineInfo, bool needMessage)
{
string str1 = needMessage ? this.Message : (string) null;
string str2 = str1 == null || str1.Length <= 0 ? this.GetClassName() : this.GetClassName() + ": " + str1;
if (this._innerException != null)
str2 = str2 + " ---> " + this._innerException.ToString(needFileLineInfo, needMessage) + Environment.NewLine + " " + Environment.GetRuntimeResourceString("Exception_EndOfInnerExceptionStack");
string stackTrace = this.GetStackTrace(needFileLineInfo);
if (stackTrace != null)
str2 = str2 + …Run Code Online (Sandbox Code Playgroud)