1

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"
}
4
  • I'm curious f you put a custom message in the annotation does it come thru? If it does it proves the annotation is the issue, otherwise something else. Commented Mar 23, 2021 at 3:19
  • just ran into the same isuue. Commented Mar 24, 2021 at 4:24
  • check you logs you have proper message in logs Commented Mar 24, 2021 at 4:47
  • @DCTID Even though I set a custom message, the response doesn't show that. Commented Mar 24, 2021 at 8:25

1 Answer 1

1

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);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.