MultipartFile 自定义注释验证

时间:2021-04-09 16:07:33

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

我有一个文件上传验证会引发 <thead> 而不是 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)]

这是 PatientProfileImageDTO

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

正确调用了 public class PatientProfileImageDTO { @CheckImageFormat @CheckImageSize private MultipartFile profileImage; public MultipartFile getProfileImage() { return profileImage; } public void setProfileImage(MultipartFile profileImage) { this.profileImage = profileImage; } } CheckFormatImage 验证器。

我需要在我的:

CheckImageSize

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

我的意思是:

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

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

我的代码有什么问题?

谢谢。

1 个答案:

答案 0 :(得分:1)

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

<块引用>

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

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

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