7

I have a FileSystemWatch program that I'm working on and if there's an error copying a file, I want to be able to know which file it failed on. At the same time, I'd like to be able to retain the stack trace, as well as the inner exception information.

                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));
                }
            }

So, the exception that gets passed, I still want to have the stacktrace info that, the inner exception info, but I want the "message" to be my custom message that contains which file it failed on, while also displaying the "real" message that was thrown by the original exception.

ganders
  • 7,285
  • 17
  • 66
  • 114

1 Answers1

13

I changed the new exception to accept ex as the inner exception instead of ex.InnerException. If you call ToString() on your new exception instance, it will include the full stack trace and all inner exceptions.

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;
}
jrummell
  • 42,637
  • 17
  • 112
  • 171