Getting value of invalid field after MethodArgumentNotValidException

家住魔仙堡 提交于 2020-02-03 08:44:49

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/36301358/getting-value-of-invalid-field-after-methodargumentnotvalidexception

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