gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 22:33:47 25 4
gpt4 key购买 nike

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

关于c# - 在保留堆栈跟踪和内部异常信息的同时抛出新异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8856012/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com