Spring Boot全局异常处理器处理MaxUploadSizeExceededException异常问题
问题场景
配置Spring Boot文件上传大小限制为10MB后,尝试通过继承ResponseEntityExceptionHandler的全局异常处理器捕获MaxUploadSizeExceededException并返回自定义响应实体,但客户端未收到预期响应,反而出现ERR_CONNECT_RESET错误。
现有配置与代码
application.yml
spring: servlet: multipart: max-file-size: 10MB max-request-size: 10MB resolve-lazily: true
全局异常处理器
@ControllerAdvice class ControllerExceptionHandler () : ResponseEntityExceptionHandler() { val log: Logger = LoggerFactory.getLogger(this::class.java) @ExceptionHandler(MaxUploadSizeExceededException::class) @ResponseStatus(HttpStatus.PAYLOAD_TOO_LARGE) protected fun uploadSizeExceptionHandler(ex: MaxUploadSizeExceededException, request: WebRequest): ResponseEntity<Any> { log.error(ex.message) return handleExceptionInternal(ex, AttachResult("Максимальный размер файла 10MB"), HttpHeaders(), HttpStatus.PAYLOAD_TOO_LARGE, request) } }
问题原因
MaxUploadSizeExceededException可能在DispatcherServlet处理请求前就被抛出:当MultipartResolver提前解析请求时,容器(如Tomcat)会直接终止超出大小的请求连接,此时异常并未进入Spring MVC的异常处理流程,导致全局异常处理器无法捕获,客户端收到连接重置错误。
另外,ResponseEntityExceptionHandler主要处理Spring MVC内部的请求处理异常,对于Multipart解析阶段的异常覆盖范围有限。
解决步骤
1. 配置容器禁止吞掉超出限制的请求
以Tomcat为例,添加容器配置,让异常能正常抛入Spring的异常处理流程:
server: tomcat: max-swallow-size: -1 # 禁用Tomcat自动截断超出大小的请求,保留异常信息
2. 调整全局异常处理器
无需继承ResponseEntityExceptionHandler,直接使用@ControllerAdvice捕获异常,并手动设置响应头确保响应正常发送:
@ControllerAdvice class ControllerExceptionHandler { val log: Logger = LoggerFactory.getLogger(this::class.java) @ExceptionHandler(MaxUploadSizeExceededException::class) fun uploadSizeExceptionHandler(ex: MaxUploadSizeExceededException, request: WebRequest): ResponseEntity<Any> { log.error("文件上传超出限制: {}", ex.message) val headers = HttpHeaders() headers.contentType = MediaType.APPLICATION_JSON return ResponseEntity(AttachResult("Максимальный размер файла 10MB"), headers, HttpStatus.PAYLOAD_TOO_LARGE) } }
3. 确认延迟解析配置生效
已配置的spring.servlet.multipart.resolve-lazily: true会让Multipart请求在Controller方法参数被解析时才处理,确保异常在Spring MVC流程内抛出,便于捕获。
其他容器适配
如果使用Jetty或Undertow,需对应调整容器的请求大小限制配置:
- Jetty:设置
server.jetty.max-form-content-size为与Spring配置一致的值 - Undertow:设置
server.undertow.max-http-post-size为与Spring配置一致的值
内容的提问来源于stack exchange,提问作者Victor Tiunov

