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

7

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

所以,我仍然希望传递的异常包含堆栈跟踪信息和内部异常信息,但我想把“message”设置为我的自定义消息,其中包含它失败的文件,并显示原始异常抛出的“真实”消息。


1
https://dev59.com/XnVD5IYBdhLWcg3wL4mM - Haris Hasan
1
你为什么要创建一个新的异常? - Oded
@Oded 所以我可以在实际的异常消息中看到出错的文件 - ganders
1个回答

13

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接