Search code examples
spring-bootreactive-programming

Spring Reactive Validation Message


Good day, I'm beginner in using spring boot webflux (reactive programming framework). Do you have an idea on how to put validation message in bad request message body. Thank you so much

image


Solution

  • You can do something like this on the layer where you validate incoming data (it's good practice to split your functionality into multiple @Service/@Component classes representing layer's: Rest Layer <-> Facade(validations) layer <-> Business logic layer <-> repository(persistence) layer):

    @Autowired private UserService userService;
    
    @Override
    public Mono<UserDatabaseModel> create(@NonNull UserDatabaseModel user) {
        return validUserOrError(user)
                .flatMap(userService::save);
    }
        
    private Mono<UserDatabaseModel> validUserOrError(@NonNull UserDatabaseModel userDatabaseModel) {
        return (userDatabaseModel.getId() == null || userDatabaseModel.getId().isBlank())
                ? monoBadRequestError("User ID cannot be null or blank")
                : Mono.defer(() -> Mono.just(userDatabaseModel));
    }
    
    private Mono<UserDatabaseModel> monoBadRequestError(@NonNull String message) {
        return Mono.error(new ResponseStatusException(HttpStatus.BAD_REQUEST, message));
    }
    

    This way if user ID is invalid error will be emitted from validUserOrError() function and all following operation's like map(), flatMap() etc .. will be skiped resulting into Http Bad Request error for that request. Otherwise result from service layer (saving user to DB) will be emmited. I personally don't use @NotBlank annotations with spring webflux as i found it not compatible in some cases and instead use structure i have provided.