2012-01-13 9 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 –

+1

を正確にあなたが新しい例外を作成しているのはなぜ? – Oded

+0

@Odedので、実際の例外メッセージにエラーがあるファイルを持つことができます – ganders

答えて

8

ex.InnerExceptionの代わりにexを内部例外として受け入れるように新しい例外を変更しました。新しい例外インスタンスで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

ありがとう@jrummell – ganders

関連する問題