I'm developing a endpoint with Spring Boot 2.1.3 (using the standard Tomcat embedded web server) to upload an image and I want to limit the size of the multipart upload. I can do this easily with the properties:
spring:
servlet:
multipart:
max-file-size: 2MB
max-request-size: 2MB
But I always get a 500 that Spring can't catch because is Tomcat that is throwing the exception and the request don't reach my code in the RestController.
2019-03-02 10:12:50.544 ERROR [] [ o.a.c.c.C.[.[.[/].[dispatcherServlet]] [] Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.web.multipart.MaxUploadSizeExceededException: Maximum upload size exceeded; nested exception is java.lang.IllegalStateException: org.apache.tomcat.util.http.fileupload.FileUploadBase$SizeLimitExceededException: the request was rejected because its size (3917946) exceeds the configured maximum (2097152)] with root cause
org.apache.tomcat.util.http.fileupload.FileUploadBase$SizeLimitExceededException: the request was rejected because its size (3917946) exceeds the configured maximum (2097152)
My ExceptionHandler is like this but obviously don't work whatever the exception that put in the annotation:
@ExceptionHandler(MaxUploadSizeExceededException.class)
public ResponseEntity handleMaxSizeException(Exception e) {
logger.warn(e.getMessage());
...
return status(HttpStatus.PAYLOAD_TOO_LARGE).body(...);
}
I already tried this with the already mentioned properties but without any effect:
@Bean
public TomcatServletWebServerFactory containerFactory() {
TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory();
factory.addConnectorCustomizers((TomcatConnectorCustomizer) connector ->
((AbstractHttp11Protocol<?>) connector.getProtocolHandler()).setMaxSwallowSize(-1));
return factory;
}
I already checked the answers in the following questions (and others...) but they are mostly outdated or simply don't work:
- Multipart file maximum size exception - spring boot embbeded tomcat
- MaxUploadSizeExceededException doesn't invoke the exception handling method in Spring
- How to handle MaxUploadSizeExceededException
Is somebody struggling with this?