Validation, Global Error Handler, and Integration Test in WebFlux
Oct 2026 · 6 min read
This article adds Bean Validation and a global error handler to movies-info-service, then proves them with WebFluxTest and DataMongoTest on top of embedded MongoDB. An invalid body yields 400 with per-field messages, an unexpected exception yields 500 without leaking details, and the old tests from CRUD Reaktif with`ReactiveMongoRepository`(https://sch39.dev/articles/spring-boot-reactive-mongo-crud) still pass without MongoDB in Docker.
Full code: https://github.com/Sch39/java-spring-boot
Problem
The CRUD from the previos article(https://sch39.dev/articles/spring-boot-reactive-mongo-crud) accepts any body: empty names, negative years, and empty cast lists are saved to MongoDB, while unhandled exceptions leak as the framework's default error. The tests also depend on MongoDB already running at localhost:27017.
Invalid data slips through: without
@Valid, the constraints on the record are never evaluated.Tests depend on infrastructure: tests that use a real MongoDB fail on machines or CI without a container.
Outcome
Readers will be able to:
Add Bean Validation constraints to the record and enable them on
@RequestBodywith@Validin Boot 4 (spring-boot-starter-validation).Map
WebExchangeBindExceptionand unexpected exceptions to 400 and 500 responses via@ControllerAdvice.Test the controller with
@WebFluxTestand the repository with@DataMongoTeston top of embedded MongoDB, including settingde.flapdoodle.mongodb.embedded.versionandspring.mongodb.port.
Implementation
Folder Structure
movies-info-service/
├── build.gradle # modified
└── src/
├── main/
│ ├── java/dev/sch39/movies_info_service/
│ │ ├── MoviesInfoServiceApplication.java
│ │ ├── MovieInfoRepository.java
│ │ ├── MovieInfoService.java
│ │ ├── MovieInfo.java # modified
│ │ ├── MovieInfoController.java # modified
│ │ └── GlobalErrorHandler.java # new
│ └── resources/application.yml
└── test/
├── java/dev/sch39/movies_info_service/
│ ├── MovieInfoControllerTest.java
│ ├── MovieInfoValidationTest.java # new
│ └── MovieInfoRepositoryTest.java # new
└── resources/config/application.yml # newSetup
Continue the project from the previous article(https://sch39.dev/articles/spring-boot-reactive-mongo-crud):
cd movies-info-serviceCode Blocks
Block 1: Validation dependency and embedded MongoDB
movies-info-service/build.gradle:
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-mongodb-reactive'
implementation 'org.springframework.boot:spring-boot-starter-webflux'
implementation 'org.springframework.boot:spring-boot-starter-validation'
testImplementation 'de.flapdoodle.embed:de.flapdoodle.embed.mongo.spring4x:4.33.0'
testImplementation 'org.springframework.boot:spring-boot-starter-validation-test'
testImplementation 'org.springframework.boot:spring-boot-starter-data-mongodb-reactive-test'
testImplementation 'org.springframework.boot:spring-boot-starter-webflux-test'
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
}Goal: Add the validation starter along with its -test counterparts, and embedded MongoDB (spring4x, a version outside the Boot BOM) for tests only.
Block 2: Constraints on the record
movies-info-service/src/main/java/dev/sch39/movies_info_service/MovieInfo.java:
package dev.sch39.movies_info_service;
import java.util.List;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Positive;
@Document
public record MovieInfo(
@Id String movieInfoId,
@NotBlank(message = "name must be present") String name,
@NotNull @Positive(message = "year must be a positive number") Integer year,
@NotEmpty(message = "cast must not be empty") List<String> cast) {
}Goal: Declare the data rules on the record component so that a single place is the source of truth for POST and PUT.
Block 3: @Valid on @RequestBody
movies-info-service/src/main/java/dev/sch39/movies_info_service/MovieInfoController.java:
import jakarta.validation.Valid;
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public Mono<MovieInfo> add(@Valid @RequestBody MovieInfo movieInfo) {
return service.add(movieInfo);
}
@PutMapping("/{id}")
public Mono<ResponseEntity<MovieInfo>> update(@PathVariable String id, @Valid @RequestBody MovieInfo movieInfo) {
return service.update(id, movieInfo)
.map(ResponseEntity::ok)
.switchIfEmpty(Mono.just(ResponseEntity.notFound().build()));
}Goal: Enable constraint evaluation before the service is called, so an invalid body produces a WebExchangeBindException.
Block 4: @ControllerAdvice for 400 and 500
movies-info-service/src/main/java/dev/sch39/movies_info_service/GlobalErrorHandler.java:
package dev.sch39.movies_info_service;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.support.WebExchangeBindException;
@ControllerAdvice
public class GlobalErrorHandler {
@ExceptionHandler(WebExchangeBindException.class)
public ResponseEntity<String> handleBindException(WebExchangeBindException ex) {
String message = ex.getBindingResult().getFieldErrors().stream()
.map(error -> error.getField() + ": " + error.getDefaultMessage())
.sorted()
.reduce((a, b) -> a + ", " + b)
.orElse("invalid request");
return ResponseEntity.badRequest().body(message);
}
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleUnexpected(Exception ex) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("internal error");
}
}Goal: Centralize exception-to-HTTP-status mapping: per-field messages for 400, and a generic message for 500 so internal details don't leak.
Block 5: Embedded MongoDB configuration for tests
movies-info-service/src/test/resources/config/application.yml:
de:
flapdoodle:
mongodb:
embedded:
version: 8.0.3
spring:
mongodb:
port: 0Goal: Choose the mongod version for embedded MongoDB and force a random port so it doesn't clash with MongoDB on 27017.
Test Blocks
Test 1: Invalid body yields 400
movies-info-service/src/test/java/dev/sch39/movies_info_service/MovieInfoValidationTest.java:
package dev.sch39.movies_info_service;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.webflux.test.autoconfigure.WebFluxTest;
import org.springframework.test.context.bean.override.mockito.MockitoBean;
import org.springframework.test.web.reactive.server.WebTestClient;
@WebFluxTest(MovieInfoController.class)
class MovieInfoValidationTest {
@Autowired
private WebTestClient client;
@MockitoBean
private MovieInfoService service;
@Test
void invalidBodyReturns400WithFieldMessages() {
String body = client.post().uri("/v1/movie-info")
.bodyValue(new MovieInfo(null, "", -1, List.of()))
.exchange()
.expectStatus().isBadRequest()
.expectBody(String.class).returnResult().getResponseBody();
System.out.println("400 body=" + body);
assertEquals("cast: cast must not be empty, name: name must be present, year: year must be a positive number",
body, "error body");
verifyNoInteractions(service);
}Goal: Prove that an invalid body is rejected with 400 containing the message for each field and that the service is never called.
Test 2: Unexpected exception yields a generic 500
movies-info-service/src/test/java/dev/sch39/movies_info_service/MovieInfoValidationTest.java:
@Test
void unexpectedExceptionReturns500WithoutLeakingDetails() {
when(service.add(any())).thenThrow(new IllegalStateException("db password=secret"));
String body = client.post().uri("/v1/movie-info")
.bodyValue(new MovieInfo(null, "Batman Begins", 2005, List.of("Christian Bale")))
.exchange()
.expectStatus().is5xxServerError()
.expectBody(String.class).returnResult().getResponseBody();
System.out.println("500 body=" + body);
assertEquals("internal error", body, "error body");
}
}Goal: Prove that the internal exception message doesn't reach the client and only internal error is returned.
Test 3: @DataMongoTest on top of embedded MongoDB
movies-info-service/src/test/java/dev/sch39/movies_info_service/MovieInfoRepositoryTest.java:
package dev.sch39.movies_info_service;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.data.mongodb.test.autoconfigure.DataMongoTest;
import reactor.test.StepVerifier;
@DataMongoTest
class MovieInfoRepositoryTest {
@Autowired
private MovieInfoRepository repository;
@Test
void saveGeneratesIdOnEmbeddedMongo() {
StepVerifier.create(repository.save(new MovieInfo(null, "Inception", 2010, List.of("Leonardo DiCaprio"))))
.assertNext(saved -> {
System.out.println("saved=" + saved);
assertNotNull(saved.movieInfoId(), "generated id");
})
.verifyComplete();
}
}Goal: Prove that the @DataMongoTest slice loads only the repository layer and saves the document to embedded mongod.
Run Test
Run from the movies-info-service/ folder (without running the tests from the previous article):
./gradlew cleanTest test -i --tests '*MovieInfoValidationTest' --tests '*MovieInfoRepositoryTest'Output:
...
MovieInfoValidationTest > invalidBodyReturns400WithFieldMessages() STANDARD_OUT
400 body=cast: cast must not be empty, name: name must be present, year: year must be a positive number
MovieInfoValidationTest > unexpectedExceptionReturns500WithoutLeakingDetails() STANDARD_OUT
500 body=internal error
...
MovieInfoRepositoryTest > saveGeneratesIdOnEmbeddedMongo() STANDARD_OUT
...
BUILD SUCCESSFUL in 19sWhy It Works
Bean Validation in WebFlux: @Valid on @RequestBody makes the argument resolver validate the object after deserialization. If there are violations, the resolver throws WebExchangeBindException before the controller method is called, so verifyNoInteractions(service) passes.
@ControllerAdvice and @ExceptionHandler: WebFlux uses the same HandlerAdapter for @RequestMapping methods and @ExceptionHandler methods, so the advice applies both to exceptions thrown by the controller and to those that surface as error signals from Mono/Flux. The more specific handler (WebExchangeBindException) wins over Exception.
Slice tests and embedded MongoDB: @WebFluxTest loads only the controller and @ControllerAdvice, so the service is mocked with @MockitoBean. @DataMongoTest loads only the MongoDB auto-configuration; flapdoodle starts a local mongod with the version from de.flapdoodle.mongodb.embedded.version and overrides the connection host/port.
Edge Cases
Validation on a null Integer field: @Positive considers null valid, so a year that isn't sent would pass if there were no @NotNull. Block 2 applies both.
Field message order: the order of FieldErrors from BindingResult isn't guaranteed, so the handler calls sorted() to make the 400 message deterministic and exactly assertable.
Tests without spring.mongodb.port: 0: the main application.yml sets port 27017, so embedded mongod tries to use the same port as MongoDB in Docker and fails to start.
Trade-offs
Strategy | Pro | Con |
|---|---|---|
Constraints on the record + | Rules in one place, | Doesn't apply to functional endpoints |
Embedded MongoDB (flapdoodle) | Tests run without Docker, random port | Downloads the mongod binary on first run, version must be set |
Real MongoDB (Docker/Testcontainers) | Behavior identical to production | Requires Docker running, slower |
Best practice: Use slice tests (@WebFluxTest, @DataMongoTest) for fast feedback, and keep one end-to-end @SpringBootTest like MovieInfoControllerTest for the full flow.
Gotchas I Encountered
Without
de.flapdoodle.mongodb.embedded.version, the test context fails withIllegalStateException: Set the de.flapdoodle.mongodb.embedded.version property or define your own IFeatureAwareVersion bean to use embedded MongoDB.With
port: 27017from the mainapplication.ymland MongoDB in Docker running, embedded mongod fails withRuntimeException: Could not start process: Address already in use;spring.mongodb.port: 0insrc/test/resources/config/application.ymlfixes it.In Boot 4 the slice test annotations live in their respective module packages:
org.springframework.boot.webflux.test.autoconfigure.WebFluxTestandorg.springframework.boot.data.mongodb.test.autoconfigure.DataMongoTest, and both come from the per-starter-testartifact.
Production Checklist
Does the 400 error message contain field names that are safe to display? Don't include sensitive input values.
Does the 500 handler log the exception? Return a generic response to the client and keep the stack trace only in the logs.
Does
de.flapdoodle.mongodb.embedded.versionmatch the production MongoDB version? Keep them the same so query behavior doesn't differ.Is
spring4xonly intestImplementation? Don't let it into the production artifact.
References
Spring Framework, WebFlux
@RequestBodyValidation: https://docs.spring.io/spring-framework/reference/web/webflux/controller/ann-methods/requestbody.htmlSpring Framework, WebFlux Exceptions: https://docs.spring.io/spring-framework/reference/web/webflux/controller/ann-exceptions.html
flapdoodle Embedded MongoDB Spring Integration, Configuration: https://github.com/flapdoodle-oss/de.flapdoodle.embed.mongo.spring