简体   繁体   中英

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

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!

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);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM