我的情况很简单,我想将例外“映射”到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;
}
这是一种优雅的编码方式?
答案 0 :(得分:3)
好吧,也许你可以在你的代码中添加一些catch,例如:
try{
//code here
}
catch(AuthenticationException e){
return HttpStatusCode.Forbidden;
}
catch(InvalidOperationException e){
return HttpStatusCode.InternalServerError;
}
catch(Exception e){
return HttpStatusCode.InternalServerError;
}
您的代码中需要的其他例外情况。
答案 1 :(得分:1)
我为地图创建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;
}