Reputation: 115
I'm trying to get Kotlin working with bean validation on spring-webflux project.
Requests seems to be validated properly, but message of a response body is empty, so it's difficult to know the cause of error.
Hot to get a default validation message from responses?
Controller:
class SomeController {
@PostMapping("/foo")
fun foo(@Valid @RequestBody body: FooRequest): Mono<FooRequest> {
return Mono.just(body)
}
}
Request:
data class FooRequest(
@field:Min(0)
val bar: Int
)
The response of calling that api with the request "{\"bar\":-1}"
is
{
"timestamp": "2021-03-23T02:18:49.368+00:00",
"path": "/api/v1/foo",
"status": 400,
"error": "Bad Request",
"message": "",
"requestId": "d1739c79-6"
}
Upvotes: 1
Views: 704
Reputation: 111
So after reading this https://www.baeldung.com/spring-boot-bean-validation
I ended up adding an exception handler like this:
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ResponseEntity<Map<String,String>> handleMethodArgumentNotValidException(MethodArgumentNotValidException exception) {
Map<String, String> errors = new HashMap<>();
exception.getBindingResult().getAllErrors().forEach((error) -> {
String fieldName = ((FieldError) error).getField();
String errorMessage = error.getDefaultMessage();
errors.put(fieldName, errorMessage);
});
return ResponseEntity
.status(HttpStatus.BAD_REQUEST)
.body(errors);
}
Upvotes: 1