有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Spring启动句柄SizeLimitExceedeException

我使用Spring boot 1.5.7
我还没有配置CommonsMultipartResolver,因为SpringBoot已经处理了文件上传

如果我的上载超过了允许的最大大小,将引发异常
这是由我的控制器处理的

@ControllerAdvice
public abstract class DefaultController implements InitializingBean {
    @ExceptionHandler(Exception.class)
    public ResponseEntity<ServiceException> handleException(final Exception ex) {
        ...
        } else if (ex instanceof MultipartException) {
            MultipartException me = (MultipartException) ex;
            Throwable cause = ex.getCause();
            if (cause instanceof IllegalStateException) {
                Throwable cause2 = cause.getCause();
                if (cause2 instanceof SizeLimitExceededException) {
                    // this is tomcat specific
                    SizeLimitExceededException slee = (SizeLimitExceededException) cause2;
                }
            }
        }

这种处理不仅复杂,而且是Tomcat特有的,因为SizeLimitExceedeException位于包org.apache.tomcat.util.http.fileupload.FileUploadBase

我如何处理这种错误情况,即无论使用哪个Servlet引擎,都会有人上传一个更大的文件,然后被允许返回一条好消息


共 (2) 个答案

  1. # 1 楼答案

    您可以在@ControllerAdvice中定义一个异常处理程序方法,该方法专门用于MultipartException,然后用一个特定的HttpStatus限定它。例如:

    @ExceptionHandler(MultipartException.class)
    @ResponseStatus(value = HttpStatus.PAYLOAD_TOO_LARGE)
    public ResponseEntity<ServiceException> handleMultipartException(MultipartException ex) {
        ...
    }
    

    这应该允许您关注“最大文件大小”异常,而无需了解servlet容器的细节

    更新1回应此评论:

    Sounds good, what about getPermittedSize and getActualSize provided by SizeLimitExceededException is there a chance to get this values not only if Tomcat is used?

    通过基于(a)异常类型和(b)HTTP状态截获此错误。。。您正在使解决方案普遍适用。但这样做可能会丢失一个servlet容器(但可能不是另一个)可能提供给您的那种详细信息。您可以通过设置^ {CD4}}来强制您自己的最大大小,在这种情况下,您将能够报告“允许的大小”,但是如果要报告“实际大小”,则必须考虑以下之一:

    • 必须使用servlet容器提供的东西
    • 选择一个小于servlet容器支持的最大值的spring.http.multipart.max-file-size,然后在控制器内应用自己的最大大小检查,并抛出自己的特定异常类型,其中包含实际大小和允许的大小
  2. # 2 楼答案

    这在我的@RestControllerAdvice中运行良好,异常比MultipartException更具体:

    @ExceptionHandler(MaxUploadSizeExceededException.class)
    @ResponseStatus(value = HttpStatus.PAYLOAD_TOO_LARGE)
    public ResponseEntity handleMultipartException(MaxUploadSizeExceededException e) {
    
        Map<String, String> result = new HashMap<>();
        result.put("message", "Error ==> Large File ");
        return  ResponseEntity.status(HttpStatus.PAYLOAD_TOO_LARGE)
                .body(result);
    
    }
    

    PS:当使用@RestControllerAdvice(annotations=RestController.class)时 这不管用。。你必须在没有RestController的情况下放置@RestControllerAdvice。类注释