统一处理许多例外情况

lys*_*cid 4 .net c# exception-handling exception

在我目前的项目中,我正在与一些第三方中间件交互,这些中间件抛出了许多不同类型的异常(大约10个异常或更多).

我使用第三方的库有几种方法,每种方法都与第三方交互,但需要保护它们不受同一组10个或更多例外的影响.

我目前拥有的是我图书馆的每个方法都是这样的:

try
{
   // some code
}
catch (Exception1 e)
{
}
catch (Exception2 e2)
{
}
  ...
catch (ExceptionN eN)
{
}
Run Code Online (Sandbox Code Playgroud)

异常的数量也可能增加.

如何减少代码重复并在一个地方统一处理所有异常?

  • 假设我的代码中每个方法的处理是相同的.

Ani*_*Ani 5

我首先捕获基Exception类型,然后使用白名单过滤:

try
{
   // Code that might throw.
}
catch (Exception e)
{
    if(e is Exception1 || e is Exception2 || e is ExceptionN) 
    {
         // Common handling code here.
    }
    else throw; // Can't handle, rethrow.
}
Run Code Online (Sandbox Code Playgroud)

现在,如果要概括过滤器,可以编写扩展名:

public static bool IsMyCustomException(this Exception e)
{
    return e is Exception1 || e is Exception2 || e is ExceptionN;
}
Run Code Online (Sandbox Code Playgroud)

然后你可以使用:

if(e.IsMyCustomException())
{
    // Common handling code here.
}
else throw;
Run Code Online (Sandbox Code Playgroud)

您可以使用一个简单的方法来概括处理程序:

private void HandleCustomException(Exception e)
{
    // Common handling code here.
}
Run Code Online (Sandbox Code Playgroud)

如果你想要概括整个try-catch块,你可能最好将一个委托注入一个包装操作的方法,如@vc 74所述.

  • 鉴于提供的额外信息,请认为这是最佳选择 - 捕获基本类型,如果可以,执行处理. (2认同)