在MethodArgumentNotValidException之后获取无效字段的值 [英] Getting value of invalid field after MethodArgumentNotValidException

查看:8229
本文介绍了在MethodArgumentNotValidException之后获取无效字段的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的实体类用hibernate的 @NotNull 来注解,我在 @ExceptionHelper 。我的问题是,我想访问无效字段的值,以便我可以将它添加到记录器。

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.

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

我已添加 @Validated 在控制器中使用 @RequestBody

I have added @Validated with the @RequestBody in the controller.

推荐答案

不会存储不正确的值,而且在前面使用实体对象是不好的做法。你应该创建一个DTO对象,而不是将它发送给你的应用程序。检查它(在这里你可以添加不正确的工作人员记录),然后处理它到你的实体对象,并尝试保存或任何你想做的事情。

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.

这篇关于在MethodArgumentNotValidException之后获取无效字段的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆