I have created the class with @ControllerAdvice to handle the exceptions and show the required messages to the user. It works fine except for RequestTooBigException. When the user tries to upload the document which size exceeds to max-request-size which is default 10MB below exception is thrown which should be handled in @ControllerAdvice

java.lang.IllegalStateException: io.undertow.server.RequestTooBigException: UT000020: Connection terminated as request was larger than 10485760

Spring Boot 2.1.8 Java 8

application.yml

  servlet:
    multipart:
      max-file-size: 10MB
@ControllerAdvice
public class FileSizeExceptionAdvice extends Throwable {

    private final Logger log = LoggerFactory.getLogger(FileSizeExceptionAdvice.class);

    @Value("${spring.servlet.multipart.max-file-size}")
    private String MAX_SIZE;

    @ExceptionHandler({MaxUploadSizeExceededException.class, MultiPartParserDefinition.FileTooLargeException.class, RequestTooBigException.class, MultipartException.class})
    public ResponseEntity invalidScriptSizeException(Exception e) {
        AbstractThrowableProblem response = new BadRequestAlertException("Max allowed size is "+MAX_SIZE, "abc", "max-size-reached");
        return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
    }
}

Comment From: bclozel

Hi @romilptl

This is the expected behavior as @ExceptionHandler annotated methods are meant to catch exceptions thrown by Controllers only (see Spring Framework reference documentation on exception handling in Spring MVC). In this case, this exception is thrown by the web server, which is at a lower level.

For more questions, please use StackOverflow. Thanks!