C#如何将详细信息附加到异常
我正在尝试处理工作功能中的异常。我的目标是只抛出一个例外,所有必要的详细信息要归功于调用功能,然后决定是否需要登录或提醒用户等。扔。这是一个简单的示例(console.writeline()
,而不是我的记录函数,为简单起见):
try
{
string arg = "[Important-Details]";
Worker(arg);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString()); //this is where I would log or pop-up message
}
这是工作函数:
public static void Worker(string details)
{
try
{
int i = 1;
int j = 0;
int k = i / j; //line90
}
catch (Exception ex)
{
Console.WriteLine($"Failed function with details:{details} - {ex.ToString()}"); //shows line90
throw; //shows this line
}
}
writeline()函数将显示LINE90(与I / J的线路)。这提供了一些有用的信息 - 我有抛出例外的确切行 - 但它并没有告诉我谁称为工人。提出此例外,我失去了我写的详细信息(“失败的功能,详细信息:{delect}”),加上将行号重置为
“ throw”
line。
尽管可以通过查看两个日志来获得所需的所有信息,但我宁愿只放弃一个例外,然后决定如何处理它。是否有一种令人震惊的方法可以做到这一点,或者什么都不能做?
I'm trying to handle exceptions being thrown in a worker function. My goal is to only throw one exception with all necessary details up to the calling function, who then decides if it needs to be logged or to alert the user, etc. But I would prefer to preserve the function and line number where the exception was thrown. Here is a simple example (Console.WriteLine()
in place of my logging function, for simplicity):
try
{
string arg = "[Important-Details]";
Worker(arg);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString()); //this is where I would log or pop-up message
}
and here is the worker function:
public static void Worker(string details)
{
try
{
int i = 1;
int j = 0;
int k = i / j; //line90
}
catch (Exception ex)
{
Console.WriteLine(quot;Failed function with details:{details} - {ex.ToString()}"); //shows line90
throw; //shows this line
}
}
The WriteLine()
inside the worker function will show line90 (line with i / j). This provides some useful information - I have the exact line where the exception was thrown - but it doesn't tell me who called the worker. Throwing up this exception, and I lose the details I wrote ("Failed function with details:{details}"), plus it resets the line number to the "throw"
line.
Although it is possible to attain all the information needed by looking at both logs, I would rather only pass up one exception and then make the decision of what to do with it. Is there a snazzy way to do this, or nothing can be done?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
解决此问题的标准方法是在
worker
函数的异常处理程序中使用Innerexception
,其中包含原始异常:这允许添加其他详细信息和保留原始异常,以便调用
ex.toString()
在调用功能中提供此输出的详细信息和原始行号:我已经在
The standard way to solve this is to threw a new exception in the exception handler of the
Worker
function with anInnerException
that contains the original exception:This allows to add additional details and preserves the original exception, so that the call to
ex.ToString()
in the calling function gives this output with both the details and the original line number:I've built a sample on dotnetfiddle; the division by zero is done in line 11 in this case.