【问题标题】:throw new Exception while keeping stack trace and inner exception information在保留堆栈跟踪和内部异常信息的同时抛出新异常
【发布时间】:2012-01-13 19:20:12
【问题描述】:

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

所以,通过的异常,我仍然想要堆栈跟踪信息,内部异常信息,但我希望“消息”是我的自定义消息,其中包含失败的文件,同时还显示原始异常引发的“真实”消息。

【问题讨论】:

标签: c# exception exception-handling


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-12
    • 1970-01-01
    • 2021-03-02
    • 2018-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多