My entity class is annotated with @NotNull
of hibernate for one of the field.I am catching the exception in @ExceptionHelper
. My problem is that i want to access the value of the invalid field so that i can add it into the logger.
Here is the ExceptionHandler
:
@ExceptionHandler({ MethodArgumentNotValidException .class })
@ResponseBody
public ResponseEntity<?> handleInvalidMethodArgException(MethodArgumentNotValidException de) {
List<FieldError> bindingResult = de.getBindingResult().getFieldErrors();
LOGGER.debug(String.format("Start : %s : handleDataexception()", this
.getClass().getSimpleName()));
for(FieldError fieldError: bindingResult){
LOGGER.debug("Invalid {} value submitted for {}",
fieldError.getRejectedValue(), fieldError.getField());
}
ErrorMsg = new ErrorMsg(errorCode, errorMessage);
return new ResponseEntity<>(errMsg, HttpStatus.NOT_FOUND);
}
I have added @Validated
with the @RequestBody
in the controller.
MethodArgumentNotValidException
has a getBindingResult
method that returns the BindingResult
if the failure is validation-related, or null
if none. So, you can call the getFieldErrors
method which returns List
of FieldError
s. Each FieldError
has a getRejectedValue
which gives you the invalid value of the corresponding field:
ex.getBindingResult().getFieldErrors().forEach(fieldError -> {
LOGGER.debug("Invalid {} value submitted for {}",
fieldError.getRejectedValue(), fieldError.getField());
});
ex
is an instance of MethodArgumentNotValidException
.
Your entity won't store incorrect values furthermore it is bad practise to use entity object on the front. You should create a DTO object, than send it to your application. Check it (here you could add incorrect staff to logger) and then process it to your entity object and try to save or whatever you want to do.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With