2

My question is regarding spring-retry. Assume a simple sample code where I have a the Service layer and Controller class.,

This is the testService Interface

public interface testService{
   @Retryable(value = { KnownExceptiomn.class }, backoff = @Backoff(delay = 1000), maxAttempts = 2)
   Address getAddress(String emailAddress);
}

This is the implementation of the service

public class testServiceImpl{
public Address getAddress(String emailAddress){
   //addressRepository is a crud repository
   return addressRepository.getAddressFromEmail(emailAddress);
   }
}

And the controller is

    @GetMapping("path/{emailId}")
    public ResponseEntity<?> getAddress(@PathVariable("emailId") final String email){
      final Address address;
      try{
        address= testService.getAddress(String emailAddress);
        if(address != null) return new ResponseEntity<Address>(address,HttpStatus.OK);

        return new ResponseEntity<String>("Invalid Email", HttpStatus.BAD_REQUEST);
        }catch(KnownException e){
   return errorMessage("Error");
       }

}

As seen the @Retryble is in the Service interface. However I have not implemented an @Recover method. My thought here was since i dont really have any secondary DB and If the DB is down there really isn't a recovery option I did not add a @Recovery method. Instead the exception was caught in the controller and handled.

My questions are:

  1. Is the above approach wrong. If so, how to do it the right way?
  2. Is it always necessary to have a recovery method? If so what would be recovery in these kind of scenarios like DB being down and no alternative source of Data.
  3. Is it wrong to catch exceptions in controller and handle them accordingly? (I was told the service lay should handle all the exceptions in some discussions).

    Everywhere I've see is some sort of recovery method but couldn't find a solid example with proper recovery handler for this type of scenario if there is.

Jens Schauder
  • 77,657
  • 34
  • 181
  • 348
Vipin Menon
  • 2,892
  • 4
  • 20
  • 35

2 Answers2

1

@Recovery is optional; if there is none, after retries are exhausted, the last exception is thrown to the caller, who has to handle the exception.

It's perfectly normal to not have a @Recovery and handle the exception in the caller, by whatever means you like.

Gary Russell
  • 166,535
  • 14
  • 146
  • 179
1

@Vipin Menon: I think you are referring to @Recover annotation, so the answer is No. @Recover annotation is provided just to give the programmer flexibility to create a recovery method to return a default (fallback) response if retry attempts also fails.

In a nutshell, don't create a recovery method using @Recover annotation if you don't need any default behavior when retry attempts fail. Simply use @Retryable annotation on the actual service method.

sapan prajapati
  • 1,514
  • 19
  • 16