gan*_*ers 5 c# exception-handling exception
我有一个我正在处理的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));
}
}
Run Code Online (Sandbox Code Playgroud)
所以,传递的异常,我仍然想要堆栈跟踪信息,内部异常信息,但我希望"消息"是我的自定义消息,其中包含失败的文件,同时还显示"真实"原始异常抛出的消息.
我更改了新的异常以接受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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10588 次 |
| 最近记录: |