We are getting different exceptions when we upload files of different sizes. The max file size allowed is 1 MB.
spring.servlet.multipart.max-file-size=1MB
When we try to upload a file of 5.95 MB we get FileSizeLimitExceededException
and when we try to upload a file of 21.5 MB we get SizeLimitExceededException
. Why are two different exceptions thrown for two different file sizes, even when both violate the pre-defined file size?
This is our custom exception handler
@Slf4j
@ControllerAdvice
@Order(2)
public class CommonErrorHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler({ SizeLimitExceededException.class })
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ResponseEntity<CommonResponse> fileSizeException(SizeLimitExceededException ex) {
CommonResponse response = new CommonResponse(String.valueOf(HttpStatus.BAD_REQUEST.value()), "File upload size exceeded SizeLimitExceededException!");
return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
}
@ExceptionHandler({ FileSizeLimitExceededException.class })
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ResponseEntity<CommonResponse> fileSizeException(FileSizeLimitExceededException ex) {
CommonResponse response = new CommonResponse(String.valueOf(HttpStatus.BAD_REQUEST.value()), "File upload size exceeded FileSizeLimitExceededException!");
return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
}
}
Due to this, we have to maintain two different methods in our exception handler. Later, we had to use the superclass of both these exceptions SizeException
to handle it in one method.So,
- Why we were getting different exceptions for different file sizes?
- Will the usage of
SizeException
be a good way to handle it?