Rahul
Rahul

Reputation: 2617

Spring boot @Valid is not returning proper message

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

    @ExceptionHandler(ConstraintViolationException.class)
    public ResponseEntity<Object> handleConstraintViolationException(ConstraintViolationException e) {
        return new ResponseEntity<Object>("ConstraintViolationException",
                HttpStatus.BAD_REQUEST);
    }

Thanks in advance 👏

Edit

I had a @RestControllerAdvice and it starts working fine, once i remove it. @RestControllerAdvice is needed in my case for the customization of exceptions.

Upvotes: 6

Views: 4082

Answers (1)

camilajenny
camilajenny

Reputation: 5064

You have to write a controller advice and return the interpolated message from the exception caught in handler for invalid method argument.

@RestControllerAdvice
public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
    @Override
    protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatusCode status, WebRequest request) {
        String bodyOfResponse = ex.getBindingResult().getFieldErrors().get(0).getDefaultMessage();
        return new ResponseEntity(bodyOfResponse, HttpStatus.BAD_REQUEST);
    }
}

And after that you should get back message msg must be present along with 400. In case you have more constraints, you should iterate over field errors, and get(0) is only for demonstration purpose.

Upvotes: 4

Related Questions