简体   繁体   English

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

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

My case is simple, I want to "map" exceptions to a HttpStatusCode. 我的情况很简单,我想将异常“映射”到HttpStatusCode。 I could easily do this: 我可以轻松做到这一点:

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

I would then add more else-if blocks checking the types. 然后,我将添加更多else-if块来检查类型。

Is there a better way of doing this? 有更好的方法吗? I can't use overloads, because the compile-time type of e is Exception , even though the runtime type will be something else. 我不能使用重载,因为e的编译时类型是Exception ,即使运行时类型是其他类型。 So this won't work (basic .NET OO): 因此,这将不起作用(基本.NET OO):

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

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

What would be an elegant way of coding this? 用什么优雅的方式编写代码?

Well, maybe you can add a few catch in your code, for example: 好吧,也许您可​​以在代码中添加一些限制,例如:

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

And another exceptions that you need in your code. 还有代码中需要的另一个例外。

I'd create a Dictionary<Type, HttpStatusCode> for the mapping: 我将为映射创建一个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