我有这个C#片段:
public class Program
{
static void Main(string[] args)
{
try
{
var ty = new Thready();
ty.Culprit();
ty.Scapegoat();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
return;
}
}
}
public class Thready
{
string state;
Exception moreInfoException;
void Scapegoat()
{
if (state != "Correct State")
throw new Exception("You called me at the wrong state!", moreInfoException);
}
void Culprit()
{
state = "Wrong State";
moreInfoException = new Exception("Here's when YOU changed the state!");
}
}
它打印此内容(请注意Culprit
异常中缺少的跟踪):
System.Exception: You called me at the wrong state! ---> System.Exception: Here's when YOU changed the state!
--- End of inner exception stack trace ---
at MyApp.Thready.Scapegoat() in C:\src\MyApp\Program.cs:line 142
at MyApp.Program.Main(String[] args) in C:\src\MyApp\Program.cs:line 20
这是一种解决方案:
public class Thready
{
string state;
private ExceptionDispatchInfo captured;
public void Scapegoat()
{
if (state != "Correct State")
{
try
{
captured.Throw();
}
catch (Exception ex)
{
throw new Exception("You called me at the wrong state!", ex);
}
}
}
public void Culprit()
{
state = "Wrong State";
try
{
throw new Exception("Here's when YOU changed the state!");
}
catch (Exception ex)
{
captured = ExceptionDispatchInfo.Capture(ex);
}
}
}
它会打印正确的迹线:
System.Exception: You called me at the wrong state! ---> System.Exception: Here's when YOU changed the state!
at MyApp.Thready.Culprit() in C:\src\MyApp\Program.cs:line 57
--- End of stack trace from previous location where exception was thrown ---
at MyApp.Thready.Scapegoat() in C:\src\MyApp\Program.cs:line 43
--- End of inner exception stack trace ---
at MyApp.Thready.Scapegoat() in C:\src\MyApp\Program.cs:line 47
at MyApp.Program.Main(String[] args) in C:\src\MyApp\Program.cs:line 22
但是,这要求我抛出异常,将其捕获并在Capture()
中调用Culprit
方法。然后在Scapegoat
中,我必须调用Throw()
,再次捕获并包装最后一个异常。看起来很慢。
是否有一种更快,更少官僚/冗长的解决方案?