如何解决MultipartFile 自定义注释验证
我有一个文件上传验证会引发 <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。
我的代码有什么问题?
谢谢。
解决方法
如果根据请求参数创建了无效对象,Spring MVC 还会抛出一个 BindException
。 MethodArgumentNotValidException
已经是 BindException
的子类。
这些实际上是故意不同的例外。 @ModelAttribute,如果不存在其他注释,则默认采用该属性,通过数据绑定和验证,并引发 BindException 以指示绑定请求属性失败或验证结果值。另一方面,@RequestBody 通过其他转换器转换请求的主体,对其进行验证并在验证失败时引发各种与转换相关的异常或 MethodArgumentNotValidException。在大多数情况下,MethodArgumentNotValidException 可以一般处理(例如通过 @ExceptionHandler 方法),而 BindException 通常在每个控制器方法中单独处理。
您可以单独处理这些错误,也可以仅捕获超类 BindException
。
@ExceptionHandler(BindException.class)
protected ResponseEntity<Object> handleBindException(BindException ex) {
// ..
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。