避免代码复制

Fla*_*nix 0 c# design-patterns exception-handling architectural-patterns

在我的代码中,我有许多带有此签名的函数(params + return类型),它们都使用同一个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);
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,这是一遍又一遍地复制,我知道复制很糟糕.发生这种情况的原因是因为我希望代码能够返回多个HttpStatusCodeResult但我不知道更好的方法.

在此示例中,我返回内部服务器错误和正常答案.但是,如果我想返回另一种类型的错误怎么办?

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

在我的代码中是否有一种模块化的行为方式,没有复制?我可以使用设计或建筑模式吗?如果是这样,哪一个?

rdu*_*com 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

并称之为:

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;
       };
}        
Run Code Online (Sandbox Code Playgroud)