Support for exception handling in R2dbcRepository, or how to decorate each method call in R2dbcRepository with my own error handler
Asked Answered
L

0

2

Background:

I have an application-wide universal exception handler to translate exceptions coming from R2dbcRepository, such as (an excerpt just to show the intended purpose):

@Component
public class ErrorHandler {
    public Throwable mapError(Throwable ex) {
        if (ex instanceof DataIntegrityViolationException || ex instanceof R2dbcDataIntegrityViolationException) {
            return new MyException(myParameters);
        }
        return new MyException(SERVER_ERROR, "Error accessing database", ex);
    }
}

Then I have an R2dbcRepository with a lot of user-defined queries, such as

import org.springframework.data.r2dbc.repository.Query;
import org.springframework.data.r2dbc.repository.R2dbcRepository;

public interface MyEntityRepository extends R2dbcRepository<MyEntity, UUID> {
    @Query("SELECT * FROM my_entity WHERE <complex conditions>")
    Flux<MyEntity> findBySomeCriteria(MyConditions myConditions);
    ...
    // Lot of other methods
}

I want to call the mapError() method after each call to any of the repository's methods, like this:

@Service
public class MyService {
    @Autowired MyEntityRepository repository;
    @Autowired ErrorHandler errorHandler;

    public Mono<MyData> getMyData(MyCriteria criteria) {
        return Mono.just(criteria)
            ... // handling the input data
            .flatMap(repository::findBySomeCriteria)
            .onErrorMap(errorHandler::mapError) // THIS IS AN UBIQUITOUS BOILERPLATE CODE
            ... // some extra business logic
            ;
    }
}

Problem Statement:

I would like to get rid of the ubiquitous boilerplate code

.onErrorMap(errorHandler::mapError)

and have it somehow built-in into the repository.

Question:

Is there an elegant solution in R2dbcRepository to register my error handle universally, so each call to any of the repository's method is automatically decorated by it?

Largish answered 24/7, 2023 at 14:7 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.