My application has following properties set
spring.http.multipart.max-file-size = 10MB
and
spring.http.multipart.max-request-size = 10MB
But instead of throwing the Springs default exception below
{ "message": "Could not parse multipart servlet request; nested exception is java.lang.IllegalStateException: org.apache.tomcat.util.http.fileupload.FileUploadBase$SizeLimitExceededException: the request was rejected because its size (12780451) exceeds the configured maximum (10485760)", "type": "MultipartException" }
I would like to throw CustomException
with message like FILE_SIZE_TOO_BIG
. Is this possible?
Can I use @ControllerAdvice
for this ?
There're a lot of ways to handle exceptions in Spring application. See exception handling in Spring MVC topic. I think GlobalControllerExceptionHandler
taken from the provided article will fit your requirements. Try this handler:
@ControllerAdvice
class GlobalControllerExceptionHandler {
@ResponseStatus(value = HttpStatus.PAYLOAD_TOO_LARGE)
@ExceptionHandler(MultipartException.class)
public void handleMultipart(MultipartException exception) {
// to do
}
}
If you get this class picked up by component scan, it should handle MultipartExceptions
thrown from any controller.