package com.linkerbot.vibemake.common; import jakarta.validation.ConstraintViolationException; import jakarta.servlet.http.HttpServletRequest; import org.apache.tomcat.util.http.fileupload.impl.FileCountLimitExceededException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.web.HttpMediaTypeNotSupportedException; import org.springframework.web.HttpRequestMethodNotSupportedException; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.MissingServletRequestParameterException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; import org.springframework.web.method.annotation.HandlerMethodValidationException; import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException; import org.springframework.web.multipart.MaxUploadSizeExceededException; import org.springframework.web.multipart.support.MissingServletRequestPartException; import org.springframework.web.servlet.resource.NoResourceFoundException; import java.util.ArrayList; import java.util.List; @RestControllerAdvice public class GlobalExceptionHandler { private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class); @ExceptionHandler(BusinessException.class) public ResponseEntity> business(BusinessException error) { // SSE 建流前也必须返回 JSON 错误,不受 Accept: text/event-stream 的限制。 ResponseEntity.BodyBuilder response = ResponseEntity.status(error.status()) .contentType(MediaType.APPLICATION_JSON) .header("Cache-Control", "no-store"); if (error instanceof RateLimitedException limited) response.header("Retry-After", Long.toString(limited.retryAfterSeconds())); return response.body(ApiResponse.failure(error)); } @ExceptionHandler({ MethodArgumentNotValidException.class, ConstraintViolationException.class, HttpMessageNotReadableException.class, HandlerMethodValidationException.class, MissingServletRequestParameterException.class, MethodArgumentTypeMismatchException.class, MissingServletRequestPartException.class }) public ResponseEntity> invalid(Exception error) { for (Throwable cause = error; cause != null; cause = cause.getCause()) if (cause instanceof RequestTooLargeException large) return business(large); return business(BusinessException.badRequest("请求参数不合法")); } @ExceptionHandler(MaxUploadSizeExceededException.class) public ResponseEntity> oversized( MaxUploadSizeExceededException error, HttpServletRequest request) { // Spring 也将 Tomcat 的表单项数量超限包装成大小异常,必须按原因区分。 List causes = new ArrayList<>(); FileCountLimitExceededException countLimit = null; for (Throwable cause = error; cause != null && causes.size() < 10; cause = cause.getCause()) { causes.add(cause.getClass().getName()); if (cause instanceof FileCountLimitExceededException exceeded) countLimit = exceeded; } log.warn("multipart 上传被拒绝 method={} path={} contentLength={} maxParts={} errorTypes={}", request.getMethod(), request.getRequestURI(), request.getContentLengthLong(), countLimit == null ? null : countLimit.getLimit(), causes); if (countLimit != null) return business(new BusinessException(413, "UPLOAD_TOO_MANY_PARTS", "上传文件或表单项数量超过限制,请减少文件后重试")); return business(new BusinessException(413, "UPLOAD_TOO_LARGE", "上传超过大小限制")); } @ExceptionHandler(HttpRequestMethodNotSupportedException.class) public ResponseEntity> method(Exception error) { return business(new BusinessException(405, "METHOD_NOT_ALLOWED", "不支持此请求方法")); } @ExceptionHandler(HttpMediaTypeNotSupportedException.class) public ResponseEntity> media(Exception error) { return business(new BusinessException(415, "UNSUPPORTED_MEDIA_TYPE", "请求内容类型不支持")); } @ExceptionHandler(NoResourceFoundException.class) public ResponseEntity> missing(Exception error) { return business(BusinessException.notFound()); } @ExceptionHandler(Exception.class) public ResponseEntity> unexpected(Exception error) { SafeExceptionLog.write(log, "未处理异常", error); return business(new BusinessException(500, "INTERNAL_ERROR", "服务暂时不可用,请提供 requestId 排查")); } }