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 exceedsmax-request-size) andFileSizeLimitExceededException(triggered when a single file exceedsmax-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
ResponseEntitywith your desired structure. But based on your question, throwingCustomExceptionaligns perfectly with your requirement. - You can add an additional
@ExceptionHandlermethod in the same@ControllerAdviceclass to handleCustomExceptionand 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

