【发布时间】:2017-06-06 10:27:15
【问题描述】:
我正在尝试使用Exception.ToString() 方法记录异常。但是,我从ToString() 方法中得到了一个新异常——它似乎源于堆栈跟踪处理。
原始错误是 FileNotFoundException。这是输出:
The process was terminated due to an unhandled exception.
Exception Info: System.IO.FileNotFoundException
at System.Signature.GetSignature(Void*, Int32, System.RuntimeFieldHandleInternal, System.IRuntimeMethodInfo, System.RuntimeType)
at System.Reflection.RuntimeMethodInfo.FetchNonReturnParameters()
at System.Reflection.RuntimeMethodInfo.GetParameters()
at System.Diagnostics.StackTrace.ToString(TraceFormat)
at System.Environment.GetStackTrace(System.Exception, Boolean)
at System.Exception.GetStackTrace(Boolean)
at System.Exception.get_StackTrace()
at System.IO.FileNotFoundException.ToString()
at InSQLMDASDriver.InSQLMDASDriver.Init(System.String, System.String)
at InSQLMDASDriver.InSQLMDASDriverLogic.InSQLMDASDriverLogicInit(System.String, System.String)
at InSQLMDASDriver.InSQLMDASDriverLogic..ctor(System.String, System.String)
at InSQLMDASDriverWCFServer.Service1.MainTread()
at System.Threading.ThreadHelper.ThreadStart_Context(System.Object)
at System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object)
at System.Threading.ThreadHelper.ThreadStart()
当我运行这段代码时,我可以验证异常是从 Exception.ToString() 中抛出的:
private void Init(string defaultWindowName, string mainPath)
{
try
{
// code that fails
}
catch(FileNotFoundException e)
{
string errorAsString = GetErrorAsString(e);
Logger.Log(string.Format("Init error at line block {0}: {1}", initBlockCounter, errorAsString), level: LogLevel.Error);
throw new Exception("FileNotFoundException: " + e.FileName + ", " + e.FusionLog, e);
}
catch (Exception e)
{
string errorAsString = GetErrorAsString(e);
Logger.Log(string.Format("Init error at line block {0}: {1}", initBlockCounter, errorAsString), level: LogLevel.Error);
throw;
}
}
string GetErrorAsString(Exception e)
{
try
{
return e.ToString();
}
catch(Exception ne)
{
return e.Message + " (ERROR getting stacktrace: " + ne.Message + ")";
}
}
为什么会发生这种情况..?
【问题讨论】:
-
你能告诉我们调用
GetErrorAsString的代码吗? -
你能证明这个例外吗?但乍一看,这可能是由于 e 对象为空。检查一下。
-
@RenatoAfonso - 如果是这种情况,
e.Message在catch(Exception ne)部分中的引用将导致再次重新抛出...... -
根据堆栈跟踪,您的代码永远不会到达
GetErrorAsString()。Exception.ToString()在任何情况下都不会抛出FileNotFoundException。 -
我猜运行时正在尝试加载在创建堆栈跟踪期间找不到的程序集。你能告诉我们 FileNotFoundException 的消息吗?