You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot中如何为MaxUploadSizeExceededException返回自定义错误信息?

解决Spring Boot文件上传超出限制时自定义错误消息不返回的问题

当你配置了spring.servlet.multipart.max-file-size和spring.servlet.multipart.max-request-size后,Tomcat默认会在检测到请求体大小超出限制时立即关闭连接,这导致Spring的@ControllerAdvice还没来得及处理MaxUploadSizeExceededException,客户端就收到了"Connection reset by peer"错误。

方法一:添加Tomcat配置属性(推荐)

在application.properties中添加以下配置,允许Tomcat接收超出限制的请求体,让Spring处理异常:

server.tomcat.max-swallow-size=-1

该配置将Tomcat的maxSwallowSize设置为-1(无限制),这样Tomcat不会因请求体过大提前关闭连接,而是将异常传递给Spring的异常处理器。

方法二:自定义Tomcat配置类(适用于需要更复杂配置的场景)

如果需要更灵活的Tomcat配置,可以创建一个配置类:

@Configuration
public class TomcatMultipartConfig {

    @Bean
    public WebServerFactoryCustomizer<ConfigurableTomcatWebServerFactory> tomcatWebServerFactoryCustomizer() {
        return factory -> factory.addConnectorCustomizers(connector -> {
            if (connector.getProtocolHandler() instanceof AbstractHttp11Protocol<?> protocolHandler) {
                // 允许Tomcat接收任意大小的剩余请求体,确保Spring能捕获异常
                protocolHandler.setMaxSwallowSize(-1);
            }
        });
    }
}

验证你的异常处理器

你的现有@ControllerAdvice类已经能正确捕获MaxUploadSizeExceededException,如果想简化写法,也可以换成@RestControllerAdvice:

@RestControllerAdvice
public class FileUploadExceptionAdvice {

    @ExceptionHandler(MaxUploadSizeExceededException.class)
    public ResponseEntity<String> handleMaxUploadSizeExceededException(MaxUploadSizeExceededException exc) {
        return ResponseEntity
                .status(HttpStatus.PAYLOAD_TOO_LARGE)
                .body("File upload failed: File too large!");
    }
}

完成以上配置后,再次测试上传超大文件,客户端就能收到你定义的自定义错误消息了。

内容的提问来源于stack exchange,提问作者Ben

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 14:09:56