Throw new Exception while saving stack traces and internal exception information

I have a FileSystemWatch program that I'm working on, and if there is an error copying the file, I want to know which file it doesn’t work with. At the same time, I would like to keep a stack trace, as well as information about internal exceptions.

                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 is being thrown, I still want to have the stack information, which is the internal information about the exception, but I want the “message” to be my special message, which contains the file with which it failed, at the same time displaying the "real" message that was selected as the original exception.

+5
source share
1 answer

, 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;
}
+8

All Articles