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

后端 未结 1 1386
情话喂你
情话喂你 2021-01-26 11:53

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

相关标签:
1条回答
  • 2021-01-26 12:37

    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);
        }
    
    0 讨论(0)
提交回复
热议问题