Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Spring 弹簧靴@Valid不';t显示来自@NotBlank的消息_Spring_Spring Boot_Rest_Validation_Post - Fatal编程技术网

Spring 弹簧靴@Valid不';t显示来自@NotBlank的消息

Spring 弹簧靴@Valid不';t显示来自@NotBlank的消息,spring,spring-boot,rest,validation,post,Spring,Spring Boot,Rest,Validation,Post,为什么不显示来自@NotBlank的消息 控制器API: @PostMapping(“/create folder”) public SuccessResponse createFolder(主体主体,@Valid@RequestBody CreateFolderRequest){ 返回historyService.createFolder(principal.getName(),request.getFolderName()); } 请求机构: @数据 公共类CreateFolderRequ

为什么不显示来自@NotBlank的消息

控制器API:

@PostMapping(“/create folder”)
public SuccessResponse createFolder(主体主体,@Valid@RequestBody CreateFolderRequest){
返回historyService.createFolder(principal.getName(),request.getFolderName());
}
请求机构:

@数据
公共类CreateFolderRequest{
@NotBlank(message=“文件夹名称是必需的。”)
私有字符串folderName;
}
JSON响应:

{
“时间戳”:“2020-11-18T11:24:19.769+00:00”,
“状态”:400,
“错误”:“错误请求”,
“消息”:“object='createFolderRequest'的验证失败。错误计数:1”,
“路径”:“/api/历史记录/创建文件夹”
}
套餐: 有效期:
import javax.validation.Valid
不空白:
import javax.validation.constraints.NotBlank


项目中没有全局异常处理程序。

@Valid throw您在@NotBlank中遇到的MethodArgumentNotValidException异常是get throw in exception details,不会返回给客户。您需要提取消息,因此请尝试将此方法添加到控制器

@ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Map<String, String> handleValidationExceptions(
            MethodArgumentNotValidException ex) {
        Map<String, String> errors = new HashMap<>();
        ex.getBindingResult().getAllErrors().forEach((error) -> {
            String fieldName = ((FieldError) error).getField();
            String errorMessage = error.getDefaultMessage();
            errors.put(fieldName, errorMessage);
        });
        return errors;
    }
@ResponseStatus(HttpStatus.BAD_请求)
@ExceptionHandler(MethodArgumentNotValidException.class)
公共地图手册例外(
MethodArgumentNotValidEx){
映射错误=新建HashMap();
例如:getBindingResult().getAllErrors().forEach((错误)->{
字符串fieldName=((FieldError)error).getField();
字符串errorMessage=error.getDefaultMessage();
errors.put(字段名、errorMessage);
});
返回错误;
}
上面的代码读取异常中的所有错误,然后获取它们的详细信息(filedName-errorMessage)并将它们放入列表中,然后将列表返回到具有400错误请求状态的clinet