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

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

问题描述

我的实体类为其中一个字段使用休眠的 @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天全站免登陆