调用可能在 catch 中抛出的方法

Yur*_*han 2 .net c#

假设我们有一个我们使用的外部服务器(例如电话站等)。我们还有下一个代码:

try
{
   externalService.CreateCall(callParams);
}
catch (Exception ex)
{
   _log.Error("Unexpected exception when trying execute an external code.", ex);
   _callService.UpdateCallState(call, CallState.Disconnected, CallOutcome.Failed);
   throw;
}
Run Code Online (Sandbox Code Playgroud)

理论上UpdateCallState可以抛出,但我们会使用该代码隐藏这个异常,并且只处理CreateCall以正确方式生成的异常。

问题是,对于这些情况,正确的模式是什么,以便我们正确对待所有异常?

Jam*_*iec 5

你总是可以try..catch在第一个捕获物内嵌套另一个并适当地处理它。

try
{
   externalService.CreateCall(callParams);
}
catch (Exception ex)
{
   _log.Error("Unexpected exception when trying execute an external code.", ex);
   try
   {
       _callService.UpdateCallState(call, CallState.Disconnected, CallOutcome.Failed);
   }
   catch(Exception updateEx)
   {
       // do something here, don't just swallow the exception
   }
   throw; // this still rethrows the original exception
}
Run Code Online (Sandbox Code Playgroud)

  • @LB - 还有?在我看来,该调用*应该*仅在 `CreateCall` 失败时进行(基于传递的参数是 `CallOutcome.Fail`)。另外,这正是 OP 代码最初的工作方式。在否决之前尝试理解问题! (2认同)