【发布时间】: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;
}
}
CheckFormatImage 和 CheckImageSize 验证器被正确调用。
我需要在我的:
@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