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

Spring Multipart文件上传超限:能否用@ControllerAdvice抛自定义异常?

Absolutely feasible! Using @ControllerAdvice is exactly the right approach to globally handle and convert Spring's default MultipartException into your custom CustomException with the FILE_SIZE_TOO_BIG message. Here's a step-by-step implementation guide:

Step 1: Define Your CustomException

First, create your custom exception class to carry the specific error message. Extending RuntimeException keeps it lightweight and compatible with Spring's exception handling:

public class CustomException extends RuntimeException {
    // Define a constant for the error message to ensure consistency
    public static final String FILE_SIZE_TOO_BIG = "FILE_SIZE_TOO_BIG";

    public CustomException(String message) {
        super(message);
    }
}

Step 2: Build the Global Exception Handler with @ControllerAdvice

Next, implement a global exception handler class annotated with @ControllerAdvice. This class will catch Spring's MultipartException, verify it's triggered by size limit violations, and then throw your CustomException:

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.multipart.MultipartException;
import org.apache.tomcat.util.http.fileupload.FileUploadBase;

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(MultipartException.class)
    public void handleMultipartSizeExceptions(MultipartException ex) throws CustomException {
        Throwable rootCause = ex.getRootCause();
        
        // Check if the exception is due to request size or individual file size exceeding limits
        if (rootCause instanceof FileUploadBase.SizeLimitExceededException 
            || rootCause instanceof FileUploadBase.FileSizeLimitExceededException) {
            throw new CustomException(CustomException.FILE_SIZE_TOO_BIG);
        }
        
        // For other MultipartException scenarios, rethrow the original exception
        throw ex;
    }
}

Key Details to Note:

  • We check both SizeLimitExceededException (triggered when total request size exceeds max-request-size) and FileSizeLimitExceededException (triggered when a single file exceeds max-file-size) to cover both of your configured limits.
  • If you want to return a formatted JSON response directly instead of throwing the exception, you can modify the handler method to return a ResponseEntity with your desired structure. But based on your question, throwing CustomException aligns perfectly with your requirement.
  • You can add an additional @ExceptionHandler method in the same @ControllerAdvice class to handle CustomException and map it to a specific HTTP status code or response body if needed.

This setup will intercept Spring's default size-related MultipartException and replace it with your custom exception carrying the FILE_SIZE_TOO_BIG message exactly as you want.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:27:28