2012-01-13 84 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

相關問題