I have a @RestController
with the following endpoint
@PutMapping
public void updateEvent(
@Valid @RequestPart EventRequest request,
@RequestPart(required = false) MultipartFile file) {
// body omitted
}
EventRequest is a standard DTO with constraints such as
@NotNull(message = "{event.endDate.empty}")
private LocalDateTime endDate;
If the request object violates any of these constraints a MethodArgumentNotValidException
is thrown, which gets converted to a list of validation errors in the response body.
Previously, any type of file could be uploaded, but now I want to restrict the types, so I made these changes:
@PutMapping
public void updateEvent(
@Valid @RequestPart EventRequest request,
@Valid @ValidFileType @RequestPart(required = false) MultipartFile file) {
// body omitted
}
ValidFileType
is a validation annotation like this one, which is mapped to a ConstraintValidator
implementation like this one.
After I’ve added these annotations, if validation of EventRequest
fails, a different exception HandlerMethodValidationException
is thrown, which doesn’t get converted to a list of validation errors.
Why does a different exception get thrown when I add validation to the file
request part, and is it possible to preserve the previous behaviour?
I’m not sure if this is relevant, but neither the endpoint method nor the @RestController
class are annotated with @Validated
.