在我的代码中,我有许多具有此签名的函数(参数 + 返回类型),它们都使用相同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);
}
}
在我的代码中是否有一种模块化的行为方式,无需复制?有我可以使用的设计或架构模式吗?如果有,是哪一个?