yongguangl
yongguangl

Reputation: 87

Springboot application.properties upload file Exception

I wrote some code in Springboot application.properties:

spring.http.multipart.max-file-size=1024KB
spring.http.multipart.max-request-size=1024KB

An exception occurs when the uploaded file is larger than the set value:

org.apache.tomcat.util.http.fileupload.FileUploadBase$SizeLimitExceededException:the request was rejected because.......

I want to capture this exception and display the custom format, what should I do?

Upvotes: 4

Views: 2187

Answers (2)

Afridi
Afridi

Reputation: 6932

To catch MultipartException related exceptions and such others, the better approach would be to create a global Exception Controller. This controller will be able to catch given exception and return a human friendly error message to client.

@ControllerAdvice
public class ExceptionController {

    NumberFormat numberFormatter = new DecimalFormat("#0.00");

    @ExceptionHandler(value = Exception.class)
    public ResponseEntity<?> handleException(Exception e) { 
        if(e instanceof MultipartException){
            String message = "Invalid form data";
            if(e.getCause() instanceof IllegalStateException){
                if(((MultipartException) e).getRootCause() instanceof SizeException){
                    SizeException sizeException = (SizeException) ((MultipartException) e).getRootCause();
                    if(sizeException instanceof FileSizeLimitExceededException){
                        FileSizeLimitExceededException cause = (FileSizeLimitExceededException) sizeException;
                        message  = "File Size should be less than: " + numberFormatter.format(cause.getPermittedSize()/Math.pow(2F, 20)) + "MB";
                    }
                    else if(sizeException instanceof SizeLimitExceededException){
                        SizeLimitExceededException cause = (SizeLimitExceededException) sizeException;
                        message  = "Request Size should be less than: " + numberFormatter.format(cause.getPermittedSize()/Math.pow(2F, 20)) + "MB";
                    }
                }
            }
            return new ResponseEntity<YourCustomResponseObject>(new 
            YourCustomResponseObject(message), 
            HttpStatus.ANY_ERROR_CODE_YOU_WANT);
             }
        }
}

Above example will help you to catch exceptions related to both Maximum file size and Maximum Request size exceptions with custom messages.

Updated

In case if you're using a file with very large size, then your browser can become un-responsive. In that case, if you are using embedded-tomcat, add below lines in your configuration file

@Bean
    public TomcatEmbeddedServletContainerFactory tomcatEmbedded() {
        TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory();
        tomcat.addConnectorCustomizers((TomcatConnectorCustomizer) connector -> {
            if ((connector.getProtocolHandler() instanceof AbstractHttp11Protocol<?>)) {
                //-1 means unlimited
                ((AbstractHttp11Protocol<?>) connector.getProtocolHandler()).setMaxSwallowSize(-1);
            }
        });
        return tomcat;
    }

But if you are using stand-alone tomcat, then change maxSwallowSize property in your server.xml file like

<Connector port="8080" protocol="HTTP/1.1"
    connectionTimeout="20000"
    redirectPort="8443" 
    maxSwallowSize="-1"/>

-1 mean maximum size of a request

Upvotes: 4

Szymon Stepniak
Szymon Stepniak

Reputation: 42184

You can use

@ExceptionHandler(FileUploadBase.SizeLimitExceededException.class)

to catch this exception and do whatever you want. There are two most common ways to use this annotation:

  • using @ControllerAdvice annotated class
  • adding a public method to your class annotated with @ExceptionHandler

Please read carefully attached reference, it describes it quite clearly. I hope it helps.

Reference: http://docs.spring.io/spring-boot/docs/1.5.5.RELEASE/reference/htmlsingle/#boot-features-error-handling

Upvotes: 1

Related Questions