当我们上传不同大小的文件时,我们会遇到不同的异常。允许的最大文件大小为 1 MB。
spring.servlet.multipart.max-file-size=1MB
当我们尝试上传 5.95 MB 的文件时,我们会得到
FileSizeLimitExceededException
;当我们尝试上传 21.5 MB 的文件时,我们会得到 SizeLimitExceededException
。为什么两个不同的文件大小会抛出两个不同的异常,即使两者都违反了预定义的文件大小?
这是我们的自定义异常处理程序
@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);
}
}
因此,我们必须在异常处理程序中维护两种不同的方法。后来,我们不得不使用这两个异常的超类
SizeException
来用一种方法来处理它。所以,
SizeException
会是处理这个问题的好方法吗?当您尝试上传超过最大允许大小的文件时,会发生文件大小超出限制的异常。某些系统或 API 支持分块上传,您可以将较大的文件分成较小的块并按顺序上传。确保您的网络连接稳定,有时网络问题可能会导致文件上传过程中出现问题
SizeLimitExceededException 是一种通用异常,当某物的大小超过预定义的限制时,可以在各种上下文中引发该异常。在代码中实现适当的错误处理以优雅地捕获和处理 SizeLimitExceededException。向用户提供有意义的错误消息或记录详细信息以供进一步调查。