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

萝らか妹 提交于 2020-07-03 12:58:08

问题


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!


回答1:


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


来源:https://stackoverflow.com/questions/62229062/how-to-do-bean-validation-with-hibernate-validation-in-spring-boot-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!