Pass service's function in controller for not duplicating try catch block

Viewed 97

I am developing REST API in Spring boot with Hibernate.

I have this function in my controller

@PostMapping("/profile")
public ResponseEntity<String> saveProfile(@Valid @RequestBody SaveProfileVM saveProfileVM,
                                          BindingResult bindingResult)
throws JsonProcessingException {

    if (bindingResult.hasErrors()) return super.fieldExceptionResponse(bindingResult);

    Profile profile;

    boolean optimisticLockException = true;
    int retryCount = 0;

    do {
        try {
            profile = accountService.saveProfile(saveProfileVM.getAccountId(),
                                                 saveProfileVM.getName(),
                                                 saveProfileVM.getEmail());

            optimisticLockException = false;
            retryCount++;

        } catch (ObjectOptimisticLockingFailureException exception) {
            retryCount++;
            System.out.println(exception.getMessage());
        }
    } while (optimisticLockException && retryCount < MAX_OPTIMISTIC_LOCK_EXCEPTION_RETRY_COUNT);

    return ResponseEntity.status(HttpStatus.OK).body(objectMapper.writeValueAsString(profile));
} 

and MAX_OPTIMISTIC_LOCK_EXCEPTION_RETRY_COUNT is 3

I don't want to duplicate the do..while and try..catch blocks in every method where I need to check ObjectOptimisticLockingFailureException

do { 
   try{} 
   catch{} 
} while()

Is there any way that I can pass accountService.saveProfile() to a general method that has the do..while and try..catch block so that I don't have to copy and paste the blocks to every method I need?

Every controller extends a BaseController so, it might be good to have the general method in BaseController?

@RestController
@RequestMapping("/account")
public class AccountController extends BaseController {

Can you guys give an idea please?

1 Answers

You can use spring-retry. More details

@Retryable(value = ObjectOptimisticLockingFailureException.class, maxAttempts = 3)
public void saveProfile(Long accountId, String name, String email){..}
Related