【问题标题】:@NotNull : validation custom message not displaying@NotNull : 验证自定义消息不显示
【发布时间】:2019-02-22 11:21:47
【问题描述】:

我正在使用 Spring Data JPA 来创建应用程序。在那我正在尝试使用注释来实现服务器端验证。我在带有自定义消息的文件上添加了 @NotNull 注释。我还添加了@valid@RequestBody

但问题是当我将nAccountId 传递为null 时,我没有收到自定义消息,即Account id can not be null 我收到“消息”:"Validation failed for object='accountMaintenanceSave'. Error count: 1",

谁能告诉我为什么我没有收到自定义消息?

控制器代码

@PutMapping("/updateAccountData")
public ResponseEntity<Object> saveData(@Valid @RequestBody AccountMaintenanceSave saveObj){
    return accService.saveData(saveObj);
} 

AccountMaintenanceSave 类

import javax.validation.constraints.NotNull;

public class AccountMaintenanceSave {   

    @NotNull(message="Account id can not be null")
    public Integer nAccountId;
    @NotNull
    public String sClientAcctId;
    @NotNull
    public String sAcctDesc;
    @NotNull
    public String sLocation;
    @NotNull
    public Integer nDeptId; 
    @NotNull
    public Integer nAccountCPCMappingid;
    @NotNull
    public Integer nInvestigatorId;

    //Getter and Setter
}

RestExceptionHandler 类

@ControllerAdvice
public class RestExceptionHandler { 

    @ExceptionHandler(Exception.class)
    public ResponseEntity<Object> handleAllExceptionMethod(Exception ex, WebRequest requset) {

        ExceptionMessage exceptionMessageObj = new ExceptionMessage();

        exceptionMessageObj.setMessage(ex.getLocalizedMessage());
        exceptionMessageObj.setError(ex.getClass().getCanonicalName());
        exceptionMessageObj.setPath(((ServletWebRequest) requset).getRequest().getServletPath());

        // return exceptionMessageObj;
        return new ResponseEntity<>(exceptionMessageObj, new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

我不知道之前到底发生了什么,也没有收到正确的消息。现在使用相同的代码得到这样的结果和正确的消息

{
  "message": "Validation failed for argument at index 0 in method: public org.springframework.http.ResponseEntity<java.lang.Object> com.spacestudy.controller.AccountController.saveData(com.spacestudy.model.AccountMaintenanceSave), with 1 error(s): [Field error in object 'accountMaintenanceSave' on field 'nAccountId': rejected value [null]; codes [NotNull.accountMaintenanceSave.nAccountId,NotNull.nAccountId,NotNull.java.lang.Integer,NotNull]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [accountMaintenanceSave.nAccountId,nAccountId]; arguments []; default message [nAccountId]]; default message [Account id can not be null]] ",
  "error": "org.springframework.web.bind.MethodArgumentNotValidException",
  "path": "/spacestudy/rockefeller/admin/account/updateAccountData"
}

message 归档中我只能打印[Account id can not be null] 吗?

【问题讨论】:

  • 你能提供你的 ExceptionHandler 类吗?我使用相同的注释@NotNull,它对我来说非常有用
  • 我添加了 ExceptionHandler 类

标签: java validation spring-data-jpa


【解决方案1】:

另一种解决方法:

我建议删除POJO 中此验证字段的exception handler,而是让Spring 通过将以下属性添加到application.properties 来处理错误响应。通过添加这个,@notnull 中配置的消息或任何验证注释可以被捕获并默认显示在响应中,并且不需要此验证案例的 explicit handling

server.error.include-message=always
server.error.include-binding-errors=always

【讨论】:

    【解决方案2】:

    试试这个。

    @ControllerAdvice
    public class RestExceptionHandler { 
    
        @ExceptionHandler(Exception.class)
        public ResponseEntity<Object> handleAllExceptionMethod(Exception ex, WebRequest requset) {
    
        ExceptionMessage exceptionMessageObj = new ExceptionMessage();
    
        // Handle All Field Validation Errors
        if(ex instanceof MethodArgumentNotValidException) {
            StringBuilder sb = new StringBuilder(); 
            List<FieldError> fieldErrors = ((MethodArgumentNotValidException) ex).getBindingResult().getFieldErrors();
            for(FieldError fieldError: fieldErrors){
                sb.append(fieldError.getDefaultMessage());
                sb.append(";");
            }
            exceptionMessageObj.setMessage(sb.toString());
        }else{
            exceptionMessageObj.setMessage(ex.getLocalizedMessage());
        }
    
        exceptionMessageObj.setError(ex.getClass().getCanonicalName());
        exceptionMessageObj.setPath(((ServletWebRequest) requset).getRequest().getServletPath());
    
        // return exceptionMessageObj;
        return new ResponseEntity<>(exceptionMessageObj, new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR);
      }
    }
    

    【讨论】:

    • 我必须用一种方法处理所有类型的异常
    • @SpringUser 我已经更新了我的答案。这将为您提供所需的输出
    • 您可以在 @ControllerAdvice 标记的类中定义其他自定义异常。所有其他未捕获的异常都将由 handleAllExceptionMethod 处理,包括那些 Validation
    【解决方案3】:

    让你的only ExceptionHandler 来捕获 Exception.class 使其成为 ConstraintViolationException.class 并不是很好

    【讨论】:

      猜你喜欢
      • 2021-06-29
      • 1970-01-01
      • 2018-06-15
      • 2014-02-21
      • 1970-01-01
      • 1970-01-01
      • 2014-08-08
      • 2017-09-30
      • 1970-01-01
      相关资源
      最近更新 更多