使用Hibernate验证和变量进入有关错误的消息

时间:2019-06-13 14:29:28

标签: spring hibernate rest validation error-handling

pom.xml 这是依赖性

<version.hibernate.validator>6.0.16.Final</version.hibernate.validator>
<dependency> <!--validation data-->
        <groupId>org.hibernate.validator</groupId>
        <artifactId>hibernate-validator</artifactId>
        <version>${version.hibernate.validator}</version>
    </dependency>

** RestErrorInfoList **

这是Java Bean。此类存储错误数据

public class RestErrorInfoList {

private Integer errorCode;

private List <String> errorMessage;


public RestErrorInfoList(Integer errorCode, List<String> errorMessage) {
    this.errorCode = errorCode;
    this.errorMessage = errorMessage;
}

ArgumentNotValidException.class

public class ArgumentNotValidException extends RuntimeException {

private BindingResult bindingResult;

public ArgumentNotValidException(BindingResult bindingResult) {
    this.bindingResult = bindingResult;
}

public BindingResult getBindingResult() {
    return bindingResult;
}

}

全局错误处理

@ControllerAdvice
 public class GlobalRestExceptionHandler extends ResponseEntityExceptionHandler {
....
@ExceptionHandler
public ResponseEntity<Object> handleException(ArgumentNotValidException    exception) {

    BindingResult bindingResult = exception.getBindingResult();
    List<FieldError> fieldErrors = bindingResult.getFieldErrors();

    List<String> errorMsg = new ArrayList<>();
    String defaultMessage;

    for (FieldError error : fieldErrors){
        defaultMessage = error.getDefaultMessage();
        errorMsg.add(defaultMessage);
    }

    RestErrorInfoList errorInfo = new RestErrorInfoList(
            HttpStatus.BAD_REQUEST.value(),
            errorMsg);

    return new ResponseEntity<>(errorInfo, HttpStatus.BAD_REQUEST);
}

}

WebConfig

    @Bean
    public MessageSource messageSource() {
    ResourceBundleMessageSource source = new    
    ResourceBundleMessageSource();
    source.setDefaultEncoding("UTF-8");
    source.setBasename("messages");
    return source;
    }

 @Nullable
 @Override
 public Validator getValidator() {
    LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
    validator.setValidationMessageSource(messageSource());
    return validator;
  }

messages.properties

 user.name.invalid = Name entered is invalid. It must be between {2} and    
 {1} characters.
  user.email.invalid = Invalid email! Please enter valid email.

休息

    @PostMapping("signup")
    public ResponseEntity<Object> saveUser (@Valid @RequestBody 
    UserFormDto userFormDto, BindingResult bindingResult){
    if (bindingResult.hasErrors()) {
        throw new ArgumentNotValidException(bindingResult);
    }

    signUpService.signUp(userFormDto);

    return ResponseEntity.ok().build();
}

dto

public class UserFormDto {

@Size(max = 20, min = 3, message = "{user.name.invalid}")
private String firstName;

@Size(max = 20, min = 3, message = "{user.name.invalid}")
private String lastName;

...

当发生错误时,客户端就会做出回应

{
"errorCode": 400,
"errorMessage": [
    "Name entered is invalid. It must be between {2} and {1} characters.",
    "Name entered is invalid. It must be between {2} and {1} characters."
]
 }

不显示实际值-{2}。

这如何纠正?

0 个答案:

没有答案