How to do Bean Validation with Hibernate Validation in Spring Boot app?
Asked Answered
T

1

2

I'm learning about Hibernate Validation in a Spring Boot app and I have a Rest controller and a POST method. And when I make a request, if a field isn't validated successfully, the client should receive 400 Bad Request and in the body a message like this "validation failed". And I try to do this, but the message didn't come.

This is the Body:

{
    "timestamp": "2020-06-06T07:56:11.377+00:00",
    "status": 400,
    "error": "Bad Request",
    "message": "",
    "path": "/ibantowallet"
}

And in the console logs I get:

2020-06-06 10:56:11.371  WARN 7552 --- [nio-8080-exec-8] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.bind.MethodArgumentNotValidException: Validation failed for argument [0] in public org.springframework.http.ResponseEntity com.dgs.demotrans.api.TransactionController.sendMoneyIbanToWallet(com.dgs.demotrans.request.IbanToWalletRequest): [Field error in object 'ibanToWalletRequest' on field 'fromIban': rejected value [FR9151000 0000 0123 4567 89]; codes [Pattern.ibanToWalletRequest.fromIban,Pattern.fromIban,Pattern.java.lang.String,Pattern]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [ibanToWalletRequest.fromIban,fromIban]; arguments []; default message [fromIban],[Ljavax.validation.constraints.Pattern$Flag;@3c555785,[a-zA-Z]{2}\d{2}[ ]\d{4}[ ]\d{4}[ ]\d{4}[ ]\d{4}[ ]\d{2}|DE\d{20}]; default message [IBAN validation failed]] ]

So the message is empty, I want the client to receive the specific message "IBAN validation failed" or "Please provide an amount", etc. How can I do that? Thank you in advance!

Talus answered 6/6, 2020 at 8:13 Comment(1)
Write an global exception handler and handle constraintsviolation exceptionsBaziotes
G
2

You would either have to create a ControllerAdvice method that handles MethodArgumentNotValidException, the error thrown by hibernate validator, like in this example:

    @ResponseStatus(BAD_REQUEST)
    @ResponseBody
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public CustomError methodArgumentNotValidException(MethodArgumentNotValidException ex) {
        BindingResult result = ex.getBindingResult();
        List<org.springframework.validation.FieldError> fieldErrors = result.getFieldErrors();
        return mapToCustomError(fieldErrors);
    }

or you can inject BindingResult in your controller method and check whether validation failed in there:

    @PostMapping("/ibantoiban")
    public ResponseEntity<String> sendMoneyIbanToIban(@Valid @RequestBody IbanToIbanRequest ibanToIbanRequest, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) { /** handle error here */ }
        Transaction transaction = transactionService.sendMoneyIbanToIban(ibanToIbanRequest);

        HttpHeaders headers = new HttpHeaders();
        headers.add("Location", "/ibantoiban" + transaction.getTransactionId().toString());
        return new ResponseEntity(headers, HttpStatus.CREATED);
    }
Gadabout answered 6/6, 2020 at 8:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.