高手请进!请教怎么处理这些重复的异常处理代码?头疼死了!

vsts2010 2010-04-20 05:01:00
项目里有很多相似的异常处理,不知道怎么可以抽取出来.像下面这样,每个方法的签名和返回值都可能不同,在try里都会调一个方法,但是在Exception中的处理是一样的。

请教该怎么做?俺们用的是3.5

public int Foo1(int p)
{
try
{
return Method1(p);
}
catch(Exception ex)
{
//在这里做完全相同的处理
throw new CustomException(ex, "Foo1");
}
}

public int Foo2(User user)
{
try
{
return Method2(user);
}
catch(Exception ex)
{
//在这里做完全相同的处理
throw new CustomException(ex, "Foo2");
}
}
...全文
140 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
vsts2010 2010-04-21
  • 打赏
  • 举报
回复
自己顶一下
vsts2010 2010-04-20
  • 打赏
  • 举报
回复
to seaonce, 没有看的很明白。。。下面是精简后实际的代码,不知道我有没有描述清楚我的意图。。。


#region Auth
#region GetAuthRequest
public AuthData GetAuthRequest(RequestKey key)
{
try
{
return AuthBLL.GetAuthRequest(key);
}
catch (FaultException<ErrorDetail>)
{
throw;
}
catch (Exception ex)
{
ErrorDetail errorDetail = new ErrorDetail();
errorDetail.Reason = ex.Message;
throw new FaultException<ErrorDetail>(errorDetail, "GetAuthRequest");
}
}
#endregion

#region ChangeAuthResponseStatus
public void ChangeAuthResponseStatus(int transactionNumber, string status)
{
try
{
AuthBLL.ChangeAuthResponseStatus(transactionNumber, status);
}
catch (FaultException<ErrorDetail>)
{
throw;
}
catch (Exception ex)
{
ErrorDetail errorDetail = new ErrorDetail();
errorDetail.Reason = ex.Message;
throw new FaultException<ErrorDetail>(errorDetail, "ChangeAuthResponseStatus");
}
}
#endregion
seaonce 2010-04-20
  • 打赏
  • 举报
回复
给你思路:
写一个EXCEPTION事件,继承事件基类,然后用泛型委托, 泛型事件基类,反射抽象,很简单的东西。
lpingz 2010-04-20
  • 打赏
  • 举报
回复
[Quote=引用 5 楼 vsts2010 的回复:]
有没有办法能够把try/catch也都确保只出现一份呢?
[/Quote]

什么意思?在主函数中try/catch?根据catch到的异常信息分化处理?
vsts2010 2010-04-20
  • 打赏
  • 举报
回复
回复2楼,3楼:上面的代码是一个例子,我的项目里,这一段代码要复杂一些
vsts2010 2010-04-20
  • 打赏
  • 举报
回复
有没有办法能够把try/catch也都确保只出现一份呢?现在的做法是把catch中的东东都抽取出来,可try/catch还是很多

现在问题是每个方法的签名都是不一样的,否则就可以定义一个delegate去干这个事情了
dlsgliss 2010-04-20
  • 打赏
  • 举报
回复
路过,帮顶!不太明白楼主意思!学习中!
ztenv 2010-04-20
  • 打赏
  • 举报
回复
很乱,Exception->CustomException,

捷哥1999 2010-04-20
  • 打赏
  • 举报
回复
你希望这些相同的处理,可以简化?还是?
throw new CustomException(ex, "Foo2");
weberwong 2010-04-20
  • 打赏
  • 举报
回复
把异常处理那块代码单独抽出来

110,539

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧