如何避免重复的try catch块
我有几个方法看起来像这样:
public void foo() { try { doSomething(); } catch(Exception e) { Log.Error(e); } }
我可以更改代码吗?
[LogException()] public void foo() { doSomething(); }
如何实现此自定义属性? 这样做的优点和缺点是什么?
—–编辑1 ————
我可以自己实现它,我的意思是只写一个类,还是我需要使用postharp或其他解决方案?
您可以使用委托和lambdas:
private void ExecuteWithLogging(Action action) { try { action(); } catch (Exception e) { Log.Error(e); } } public void fooSimple() { ExecuteWithLogging(doSomething); } public void fooParameter(int myParameter) { ExecuteWithLogging(() => doSomethingElse(myParameter)); } public void fooComplex(int myParameter) { ExecuteWithLogging(() => { doSomething(); doSomethingElse(myParameter); }); }
实际上,您可以将ExecuteWithLogging
重命名为ExecuteWebserviceMethod
并添加其他常用的东西,例如检查凭据,打开和关闭数据库连接等。
您可以尝试使用: PostSharp
或尝试谷歌’AOP’ – ‘面向方面编程’。 网上有更多类似的技术。
由于您提到您正在使用WCF,因此您可以实现IErrorHandler接口,并且所有exception都将路由到您可以记录它们的方法。
如果您不想使用AOP方法,那么我以前的一个雇主在一组类中使用常见exception处理的方法是使用类似于以下方法的基类
protected TResult DoWrapped(Func action) { try { return action(); } catch (Exception) { // Do something throw; } }
方法看起来像。
public object AMethod(object param) { return DoWrapped(() => { // Do stuff object result = param; return result; }); }
记不清楚,已经有一段时间了。 但与此类似。