0

在我的代码中,我有许多具有此签名的函数(参数 + 返回类型),它们都使用相同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);
    }
}

在我的代码中是否有一种模块化的行为方式,无需复制?有我可以使用的设计或架构模式吗?如果有,是哪一个?

4

1 回答 1

7

您可以像这样进行分解:

public static class Helper
{
    public static ActionResult TryCatch(Func<ActionResult> funk)
    {
        try
        {
            if (funk != null)
            {
                ActionResult result = funk();
                if (result != null)
                    return result;
            }
        }
        catch (Exception ex)
        {
            return new HttpStatusCodeResult(HttpStatusCode.InternalServerError, ex.Message);
        }
        return new HttpStatusCodeResult(HttpStatusCode.OK);
    }
}

并这样称呼它:

public ActionResult methodName(int id)
{
    return Helper.TryCatch(() => 
       {
            //Some specific code here
            if(conditionA)
                return return new HttpStatusCodeResult(HttpStatusCode.NotFound, "No Hamsters found!")
            return null;
       };
}        
于 2015-03-03T10:44:06.800 回答