Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting value of invalid field after MethodArgumentNotValidException

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.

like image 554
Spring User Avatar asked Mar 30 '16 06:03

Spring User


2 Answers

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 FieldErrors. 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.

like image 148
Ali Dehghani Avatar answered Oct 31 '22 20:10

Ali Dehghani


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. enter image description here

like image 39
pokemzok Avatar answered Oct 31 '22 20:10

pokemzok