Home > database >  Intercept exceptions thrown by repository method with different error codes
Intercept exceptions thrown by repository method with different error codes

Time:10-20

Is there a way to intercept DataAccessException that is thrown by data-layer (@Repository) with knowing which method is causing this exception?

Writing custom SQLExceptionTranslator does not fit my need as I cannot determine which method caused the exception.

I have a repository like this:

public interface UserRepository extends JpaRepository<UserEntity, Integer> {
    @ErrorCode("E1000")
    User findById(int id);
    
    @ErrorCode("E1001")
    User findByUsername(String username);
}

ErrorCode is a custom annotation holds an error code that I need to send to client whenever DataAccessException occurs.

If there is a way to intercept the call to findById with catching DataAccessException, then it is easy to extract error code from annotation and re-throw a custom exception that can be catched by exception handler.

CodePudding user response:

If Spring AOP is allowed, you could build your own aspect, for example:

@Aspect
public class ErrorCodeAspect {

    @Around("@annotation(errorCode)")
    public Object aroundErrorCode(ProceedingJoinPoint joinPoint, ErrorCode errorCode) throws Throwable {
        try {
            return joinPoint.proceed();
        } catch (DataAccessException dae) {
            throw new YourCustomException(errorCode.value(), dae);
        }
    }

}

Note that annotations on interface methods are not inherited by implementing class methods (even with @Inherited which applies to parent classes only), so you will probably need to annotate your concrete service classes instead for the aspect to plug in (unless Spring does some additional black magic with the repository proxies I wouldn't be aware of).

CodePudding user response:

You can define the custom ExceptionHandler.

@RestControllerAdvice
public class RestExceptionResolver {
    @ExceptionHandler(DataAccessException.class)
    public ResponseEntity<String> handleNoSuchElementException(DataAccessException ex) {
        return ResponseEntity.status(yourErrorCode);
    }
}
  • Related