Pallavi Singh
Pallavi Singh

Reputation: 75

Sonar Showing issue if I used "instanceof" operator in catch block

How can I refactor below catch block I am using java11 Code

public String methodName(ClassRequest request, Destination ABC) {
        try {
          <Some Code Here>
        } catch (Exception e) {
            log.error("error", ABC, e);
            if(e instanceof ABCRestException ||
                    (ABC == PREM && (e instanceof HttpServerErrorException || e instanceof HttpClientErrorException))) {
                throw e;
            } else if(e instanceof HttpServerErrorException) {
                throw new ABCRestException(request.getAId(), "unexpected_error", "Some Message", e, INTERNAL_SERVER_ERROR);
            } else if(e instanceof HttpClientErrorException) {
                throw new ABCRestException(request.getAId(), "missing_field", "Some Message", e, BAD_REQUEST);
            } else {
                throw new ABCRestException(request.getAId(), "unexpected_error", "Some Massage", e, INTERNAL_SERVER_ERROR);
            }
        }
    }

How I can refactor this code Means catch block

Upvotes: 0

Views: 1128

Answers (1)

Javier Toja
Javier Toja

Reputation: 1762

you just need two catch blocks like this

public String methodName(ClassRequest request, Destination ABC) {
        try {
          <Some Code Here>
        } catch (HttpServerErrorException e) {
            log.error("error", ABC, e);
            
            if (ABC == PREM){
             throw e;
            }else{
              throw new ABCRestException(request.getAId(), "unexpected_error", "Some Message", e, INTERNAL_SERVER_ERROR);
            }
        } catch (HttpClientErrorException e){
            if (ABC == PREM){
             throw e;
            }else{
               throw new ABCRestException(request.getAId(), "missing_field", "Some Message", e, BAD_REQUEST);
            }
        }
    }

If you want to reuse some logic, you can write a private method and invoke it inside the catch block

If two or more exceptions share the same exact logic you can also use a multi-catch which will catch various exceptions in the same block

try{
   codeGoesVroomVroomAndThrows()
}catch(ExceptionA | ExceptionB e){
  //do something
}

Upvotes: 4

Related Questions