2012-01-13 83 views
5

我有一个FileSystemWatch程序,我正在处理,如果有错误复制文件,我想能够知道哪个文件失败。同时,我希望能够保留堆栈跟踪以及内部异常信息。抛出新的异常,同时保持堆栈跟踪和内部异常信息

   if (!found) 
      { 
       try 
       { 
        File.Copy(file, Path.Combine(watchDirectory, filename)); 
       } 
       catch (Exception ex) 
       { 
        WriteToLog(new Exception(
         String.Format("An error occurred syncing the Vault location with the watch location. Error copying the file {0}. Error = {1}", file, ex.Message), ex.InnerException)); 
       } 
      } 

所以,这被传递例外,我还是希望有堆栈跟踪信息是,内部异常的信息,但我想要的“消息”是包含哪些文件,它失败了我的自定义消息,同时还显示原始异常引发的“真实”消息。

+1

http://stackoverflow.com/questions/57383/in-c-how-can-i-rethrow-innerexception-without-losing-stack-trace – 2012-01-13 19:23:57

+1

为什么你到底是创建新的异常? – Oded 2012-01-13 19:29:57

+0

@Oded所以我可以在实际的异常消息中出现错误的文件 – ganders 2012-01-13 22:51:07

回答

8

我改变了新的异常,接受ex作为内部异常而不是ex.InnerException。如果在新的异常实例上调用ToString(),它将包含完整的堆栈跟踪和所有内部异常。

try 
{ 
    // ... 
} 
catch (Exception ex) 
{ 
    string message = String.Format("An error occurred syncing the Vault location with the watch location. Error copying the file {0}.", file); 
    Exception myException = new Exception(message, ex); 
    string exceptionString = myException.ToString(); // full stack trace 
    //TODO: write exceptionString to log. 
    throw myException; 
} 
+0

Thanks @ jrummell – ganders 2012-01-13 22:53:08

相关问题