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