抛出新的异常,同时保留堆栈跟踪和内部异常信息

本文关键字:异常 跟踪 堆栈 信息 内部 保留 | 更新日期: 2023-09-27 18:20:11

我正在处理一个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));
                }
            }

所以,对于传递的异常,我仍然希望有堆栈跟踪信息,内部异常信息,但我希望"消息"是我的自定义消息,包含它在哪个文件上失败,同时还显示原始异常引发的"真实"消息。

抛出新的异常,同时保留堆栈跟踪和内部异常信息

我更改了新异常,接受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;
}