在保持堆栈跟踪和内部异常信息的同时引发新异常 [英] throw new Exception while keeping stack trace and inner exception information

查看:83
本文介绍了在保持堆栈跟踪和内部异常信息的同时引发新异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个正在使用的FileSystemWatch程序,如果复制文件时出错,我希望能够知道该文件在哪个文件上失败。同时,我希望能够保留堆栈跟踪以及内部异常信息。

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

所以,通过的异常我仍然想要具有内部异常信息的stacktrace信息,但我希望消息是我的自定义消息,其中包含失败的文件,同时还要显示原始异常抛出的真实消息。

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.

推荐答案

我将新异常更改为接受ex作为内部异常,而不是ex.InnerException。如果在新的异常实例上调用ToString(),它将包括完整的堆栈跟踪和所有内部异常。

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

这篇关于在保持堆栈跟踪和内部异常信息的同时引发新异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆