在我当前的项目中,我正在与一些第三方中间件进行交互,它会抛出许多不同类型的异常(大约10个异常或更多)。
我的库是使用第三方有几个方法,每一个与第三方互动,但需要保护不受相同的一组10或更多的例外。
我现在拥有的是类似于的东西--库中的每一种方法:
try
{
// some code
}
catch (Exception1 e)
{
}
catch (Exception2 e2)
{
}
...
catch (ExceptionN eN)
{
}例外的数目也可能增加。
如何减少代码重复,并在一个地方统一处理所有异常?
发布于 2011-12-14 13:41:51
可以使用全局异常处理程序,实现取决于项目类型(ASP.net -> global.asax,WPF -> App.xaml.)
或者使用如下内容:
private static void HandleExceptions(Action action)
{
try
{
action();
}
catch (Exception1 e)
{
}
catch (Exception2 e2)
{
}
...
catch (ExceptionN eN)
{
}
}它可以以下列方式调用:
HandleExceptions(() => Console.WriteLine("Hi there!"));如果在Console.WriteLine执行过程中引发异常,则将由异常处理逻辑处理它。
请注意,要执行的代码还可能修改外部值:
int x = 2;
HandleExceptions(() => x = 2 * x);如果您更喜欢匿名方法:
var x = 2;
HandleExceptions(delegate()
{
x = x * 2;
});发布于 2011-12-14 13:39:38
我首先捕获基本的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.
}现在,如果要泛化筛选器,可以编写一个扩展:
public static bool IsMyCustomException(this Exception e)
{
return e is Exception1 || e is Exception2 || e is ExceptionN;
}然后你就可以用:
if(e.IsMyCustomException())
{
// Common handling code here.
}
else throw;您可以使用一个简单的方法来概括处理程序:
private void HandleCustomException(Exception e)
{
// Common handling code here.
}如果您想要泛化整个try-catch块,最好将委托注入到包装操作的方法中,如@vc 74所述。
发布于 2011-12-14 13:48:03
如何使用一个函数来处理这些异常:
try
{
//Some code here
}
catch(Exception e)
{
if(!ErrorHandler(e))
return null; //unhandled situation
}
private bool ErrorHandler(Exception e)
{
switch(e)
{
case Exception1:
//Handle the exception type here
return true;
case Exception2:
//Handle another exception type here
return true;
}
return false;
}https://stackoverflow.com/questions/8505379
复制相似问题