1

I have an exception handling code that i think that it violates Open/Closed Principle. Because of these exceptions derived from system.exception i can not find a way for applying Open closed principle like the classical Shape example (http://joelabrahamsson.com/a-simple-example-of-the-openclosed-principle/)

Could you please help me about refactoring this code block

        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;
        }

And this is another method;

    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;
        }
    }

0 Answers0