【发布时间】:2015-05-03 23:15:39
【问题描述】:
在我的代码中,我有许多具有此签名的函数(参数 + 返回类型),它们都使用相同的 try-catch 子句。
public ActionResult methodName(int id)
{
try
{
//Some specific code here
return new HttpStatusCodeResult(HttpStatusCode.OK);
}
catch (Exception ex)
{
return new HttpStatusCodeResult(HttpStatusCode.InternalServerError, ex.Message);
}
}
现在,这被一遍又一遍地复制,我知道复制是不好的。
发生这种情况的原因是因为我希望代码能够返回多个HttpStatusCodeResult,但我不知道更好的方法。
在本例中,我返回一个内部服务器错误和一个 OK 答案。但是如果我想返回另一种类型的错误呢?
public ActionResult methodName(int id)
{
try
{
//Some specific code here
if(conditionA)
return return new HttpStatusCodeResult(HttpStatusCode.NotFound, "No Hamsters found!")
return new HttpStatusCodeResult(HttpStatusCode.OK);
}
catch (Exception ex)
{
return new HttpStatusCodeResult(HttpStatusCode.InternalServerError, ex.Message);
}
}
在我的代码中是否有一种无需复制的模块化方式来实现行为?有我可以使用的设计或架构模式吗?如果有,是哪一个?
【问题讨论】:
-
使用异常过滤器代替
try..catch。 -
你能举个例子吗?我不知道你在说什么:S
-
复制与创建异常有关,而不是处理它们。过滤器不会做:S
-
您可以删除
try..catch块并使用过滤器来过滤return new HttpStatusCodeResult(HttpStatusCode.InternalServerError, ex.Message);,以防出现异常。然后你就剩下if (condA) { return new (...) } else { return new (...) }。如果您甚至不想这样,您可以在变量中设置状态代码和文本,然后return new HttpStatusCodeResult(statusCode, statusText)... 在每个操作方法中重复此操作。
标签: c# design-patterns exception-handling architectural-patterns