【问题标题】:MultipartFile custom annotations validationMultipartFile 自定义注释验证
【发布时间】:2021-04-09 16:07:33
【问题描述】:

我的文件上传验证会引发 BindException 而不是 MethodArgumentNotValidException,我不明白为什么。

  org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'patientProfileImageDTO' on field 'profileImage': rejected value [org.springframework.web.multipart.commons.CommonsMultipartFile@2840a305]; codes [CheckImageFormat.patientProfileImageDTO.profileImage,CheckImageFormat.profileImage,CheckImageFormat.org.springframework.web.multipart.MultipartFile,CheckImageFormat]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [patientProfileImageDTO.profileImage,profileImage]; arguments []; default message [profileImage]]; default message [Invalid image format (allowed: png, jpg, jpeg)]

我的控制器是:

@PostMapping("/patient/image")
public ResponseEntity<?> updateProfileImage(@Validated PatientProfileImageDTO patientProfileImageDTO)

这是 PatientProfileImageDTO

public class PatientProfileImageDTO {
        
    @CheckImageFormat   
    @CheckImageSize
    private MultipartFile profileImage;
    
    public MultipartFile getProfileImage() {
        return profileImage;
    }
    
    public void setProfileImage(MultipartFile profileImage) {
        this.profileImage = profileImage;
    }

}

CheckFormatImageCheckImageSize 验证器被正确调用。

我需要在我的:

@ControllerAdvice
public class ApiExceptionHandler {
        
        ExceptionHandler(MethodArgumentNotValidException.class)
        protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, WebRequest request) {
        
        ...
        }
    }

我的代码的另一部分中还有其他自定义验证注释,它们按预期工作。

我的意思是:

@OldPasswordMatch(message = "old password mismatch")
private String oldPassword;

这个自定义验证会触发我想要的 MethodArgumentNotValidException。

我的代码有什么问题?

谢谢。

【问题讨论】:

    标签: java spring validation hibernate-validator spring-validator


    【解决方案1】:

    如果从请求参数创建了无效对象,Spring MVC 还会抛出 BindExceptionMethodArgumentNotValidException 已经是 BindException 的子类。

    这些实际上是故意不同的例外。 @ModelAttribute,如果不存在其他注释,则默认情况下假定它会通过数据绑定和验证,并引发 BindException 以指示绑定请求属性或验证结果值失败。另一方面,@RequestBody 通过其他转换器转换请求的主体,对其进行验证并引发各种与转换相关的异常或在验证失败时引发 MethodArgumentNotValidException。在大多数情况下,可以通用处理 MethodArgumentNotValidException(例如通过 @ExceptionHandler 方法),而 BindException 通常在每个控制器方法中单独处理。

    您可以单独处理这些错误,也可以只捕获超类BindException

    @ExceptionHandler(BindException.class)
    protected ResponseEntity<Object> handleBindException(BindException ex) {
        // ..
    }
    

    【讨论】:

    • 谢谢,这正是我在发布问题几分钟后所做的。我发现了 BindException。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多