我有一个异常处理代码,我认为它违反了开放/封闭原则。由于从system.exception派生的这些异常,我无法找到一种方法来应用Open闭合原则,如经典的Shape示例(http://joelabrahamsson.com/a-simple-example-of-the-openclosed-principle/)
请你帮我解释一下这个代码块的重构
switch (exception)
{
case DuplicateNameException _:
returnMessage = DefaultResponseMessages.RecordExistsError;
break;
case KeyNotFoundException _:
returnMessage = DefaultResponseMessages.NotFoundError;
break;
case ArgumentException _:
returnMessage = DefaultResponseMessages.ArgumentExceptionError;
break;
case AuthenticationException _:
returnMessage = DefaultResponseMessages.LoginError;
detailMessage = string.Empty;
break;
case UnauthorizedAccessException _:
returnMessage = DefaultResponseMessages.UnauthorizedAccessError;
detailMessage = string.Empty;
break;
}
这是另一种方法;
public static HttpStatusCode ExceptionToStatusCode(this Exception exception)
{
switch (exception)
{
case KeyNotFoundException _:
return HttpStatusCode.NotFound;
case DuplicateNameException _:
return HttpStatusCode.BadRequest;
case ArgumentException _:
return HttpStatusCode.BadRequest;
case UnauthorizedAccessException _:
return HttpStatusCode.Unauthorized;
default:
return HttpStatusCode.InternalServerError;
}
}