繁体   English   中英

根据运行时类型重载或避免if-else / switch-case

[英]Overloading based on runtime type or avoiding if-else/switch-case

我的情况很简单,我想将异常“映射”到HttpStatusCode。 我可以轻松做到这一点:

if (e is AuthenticationException)
{
    return HttpStatusCode.Forbidden;
}
else
{
    return HttpStatusCode.InternalServerError;
}

然后,我将添加更多else-if块来检查类型。

有更好的方法吗? 我不能使用重载,因为e的编译时类型是Exception ,即使运行时类型是其他类型。 因此,这将不起作用(基本.NET OO):

private static HttpStatusCode GetHttpStatusCode(Exception e)
{
    return HttpStatusCode.InternalServerError;
}

private static HttpStatusCode GetHttpStatusCode(AuthenticationException e)
{
    return HttpStatusCode.Forbidden;
}

用什么优雅的方式编写代码?

好吧,也许您可​​以在代码中添加一些限制,例如:

try{
    //code here
}
catch(AuthenticationException e){
    return HttpStatusCode.Forbidden;
}
catch(InvalidOperationException e){
    return HttpStatusCode.InternalServerError;
}
catch(Exception e){
    return HttpStatusCode.InternalServerError;
}        

还有代码中需要的另一个例外。

我将为映射创建一个Dictionary<Type, HttpStatusCode>

var dict = new Dictionary<Type, HttpStatusCode>
{
    { typeof(AuthenticationException), HttpStatusCode.Forbidden },
    // etc.
}

HttpStatusCode GetStatusCodeFromException(Exception e)
{
    HttpStatusCode code;
    if (!dict.TryGetValue(e.GetType(), out code))
        code = // Whatever default value you want
    return code;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM