package com.custom.webui.exception; import com.custom.webui.dto.resp.Result; import lombok.extern.slf4j.Slf4j; import jakarta.servlet.http.HttpServletRequest; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.validation.BindException; import org.springframework.validation.FieldError; 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.multipart.MaxUploadSizeExceededException; import java.util.stream.Collectors; /** * 全局异常处理器。 * *
把各类异常统一收敛成 {@code {code, msg, data}} 结构,避免前端需要处理多种错误格式。 * 注意:SSE 接口不走这里 —— 流已经以 text/event-stream 提交后无法再改写 HTTP 状态, * 流内错误由 MessageController 以 {@code event: error} 事件下发。 */ @Slf4j @RestControllerAdvice public class GlobalExceptionHandler { /** * 业务异常:按异常自带的 code 映射 HTTP 状态。 * *
这里要处理一个 SSE 特有的坑:{@code GET /api/chats/{id}/stream} 声明了 * {@code produces=text/event-stream},浏览器的 fetch 也带着 * {@code Accept: text/event-stream}。当业务校验在流开始前就失败时, * 若按普通 JSON 返回,内容协商会因为「客户端不接受 application/json」而抛 * {@code HttpMediaTypeNotAcceptableException},最终用户看到的是一个 * 毫无信息量的 HTTP 500,而不是「消息内容不能为空」这种可操作的提示。 * *
因此对 SSE 请求显式用 text/plain 输出错误正文(fetch 能读到,
* 前端的错误分支会把它显示出来)。
*/
@ExceptionHandler(BusinessException.class)
public ResponseEntity> handleBusiness(BusinessException e, HttpServletRequest request) {
log.warn("业务异常 code={} msg={}", e.getCode(), e.getMessage());
HttpStatus status = HttpStatus.resolve(e.getCode());
HttpStatus resolved = status == null ? HttpStatus.INTERNAL_SERVER_ERROR : status;
if (isEventStreamRequest(request)) {
return ResponseEntity.status(resolved)
.contentType(MediaType.TEXT_PLAIN)
.body(e.getMessage());
}
return ResponseEntity.status(resolved).body(Result.error(e.getCode(), e.getMessage()));
}
/** 判断该请求是否在等 SSE 流(据此决定错误响应的内容类型) */
private boolean isEventStreamRequest(HttpServletRequest request) {
if (request == null) {
return false;
}
String accept = request.getHeader(HttpHeaders.ACCEPT);
return accept != null && accept.contains(MediaType.TEXT_EVENT_STREAM_VALUE);
}
/** @Valid 校验失败:把字段错误拼成一句可读提示 */
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity