如何明确不抛出异常? [英] How to be explicit about NOT throwing an exception?

查看:122
本文介绍了如何明确不抛出异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是一个广泛的问题,但最近我想知道以下内容:在我们的C#后端中,我们有很多地方将某些代码包装在try/catch块中,特别是对外部WcF服务的调用.其中一些调用对于应用程序至关重要,因此在catch块中,我们记录错误并重新抛出,例如:

This might be a broad question, but recently I ahve wondered about the following: In our C# backend we have many places that wrap some code in a try/catch block, specifically calls to external WcF services. Some of these calls are crucial for the application so in the catch block we log the error and rethrow, like:

catch(Exception ex)
{
    _logger.Error("Some good error message");
    throw ex;
}

另一方面,有些服务允许我们失败,但是我们仍然想记录错误,因此它们看起来像:

On the other hand there are services we allow to fail, but we still want to log the error, so they look like:

catch(Exception ex)
{
    _logger.Error("Some good error message");
}

现在正在阅读团队成员的代码,我不确定他们是否忘记了扔了或者这是否是预期的行为.

Now reading the code of team members I can not be sure if they forgot to throw or if this is the intended behaviour.

问:,有办法吗?显式不重新抛出(不包含代码中的注释)的默认方法是什么.

Q: Is there a way, resp. what is the default way, to explicitly NOT rethrow (without including a comment in the code).

我考虑过这样的事情:

catch(Exception ex)
{
    _logger.Error("Some good error message");
    NotThrowingHereOnPurpose();
}

// ...
// and further below a private method
// ...

private void NotThrowingHereOnPurpose(){}

推荐答案

我实际上找到了另一种方法,其中包括其他人在此处提出的建议,但是使用了内置功能:异常过滤器.我可以随意修改这里进行说明:

I actually found another way that kind of includes what other have suggested here, but uses a built in feature: exception filters. I was free to modify the example given in here to illustrate this:

public void MethodThatFailsSometimes()
{
    try {
        PerformFailingOperation();
    } 
    catch (Exception e) when (e.LogAndBeCaught())
    {
    }
}

,然后可以在Exception上有两种扩展方法,例如LogAndBeCaughtLogAndEscape:

and then one could have two extension methods on Exception, say LogAndBeCaught and LogAndEscape like so:

public static bool LogAndBeCaught(this Exception e)
{
    _logger.Error(@"Following exception was thrown: {e}");
    return true;
} 

public static bool LogAndEscape(this Exception e)
{
    _logger.Error(@"Following exception was thrown: {e}");
    return false;
} 

这篇关于如何明确不抛出异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆