Home > OS >  Spring boot @Valid is not returning proper message
Spring boot @Valid is not returning proper message

Time:02-03

Controller Method

    @PostMapping("/hello")
    public Hello hello(@Valid @RequestBody  Hello hello) {
        return hello;
    }

POJO

import jakarta.validation.constraints.NotBlank;


class Hello{
    @NotBlank(message = "msg must be present")
    String msg;

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }
    
}

Upon hitting the above URL with the following payload

{
    "msg":""
}

I am getting the following response.

{
    "type": "about:blank",
    "title": "Bad Request",
    "status": 400,
    "detail": "Invalid request content.",
    "instance": "/hello"
}

It should ideally specify the message msg must be present.

What's wrong here?

enter image description here

The following things have been already tried

  • added server.error.include-message: always in application.properties file
    @ExceptionHandler(ConstraintViolationException.class)
    public ResponseEntity<Object> handleConstraintViolationException(ConstraintViolationException e) {
        return new ResponseEntity<Object>("ConstraintViolationException",
                HttpStatus.BAD_REQUEST);
    }

Thanks in advance

  • Related