kongdeqiang
2026-10-14 9f9e043849b6f497e00399900ff234cf097eba82
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
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;
 
/**
 * 全局异常处理器。
 *
 * <p>把各类异常统一收敛成 {@code {code, msg, data}} 结构,避免前端需要处理多种错误格式。
 * 注意:SSE 接口不走这里 —— 流已经以 text/event-stream 提交后无法再改写 HTTP 状态,
 * 流内错误由 MessageController 以 {@code event: error} 事件下发。
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
 
    /**
     * 业务异常:按异常自带的 code 映射 HTTP 状态。
     *
     * <p>这里要处理一个 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,而不是「消息内容不能为空」这种可操作的提示。
     *
     * <p>因此对 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<Result<Void>> handleValidation(MethodArgumentNotValidException e) {
        String msg = e.getBindingResult().getFieldErrors().stream()
                .map(FieldError::getDefaultMessage)
                .collect(Collectors.joining("; "));
        return ResponseEntity.badRequest().body(Result.error(400, msg.isBlank() ? "参数校验失败" : msg));
    }
 
    @ExceptionHandler(BindException.class)
    public ResponseEntity<Result<Void>> handleBind(BindException e) {
        String msg = e.getBindingResult().getFieldErrors().stream()
                .map(FieldError::getDefaultMessage)
                .collect(Collectors.joining("; "));
        return ResponseEntity.badRequest().body(Result.error(400, msg.isBlank() ? "参数绑定失败" : msg));
    }
 
    @ExceptionHandler(MissingServletRequestParameterException.class)
    public ResponseEntity<Result<Void>> handleMissingParam(MissingServletRequestParameterException e) {
        return ResponseEntity.badRequest()
                .body(Result.error(400, "缺少必需参数: " + e.getParameterName()));
    }
 
    /** 上传超限:Spring 层限制,早于业务校验触发 */
    @ExceptionHandler(MaxUploadSizeExceededException.class)
    public ResponseEntity<Result<Void>> handleMaxUpload(MaxUploadSizeExceededException e) {
        return ResponseEntity.badRequest().body(Result.error(400, "文件超过大小限制"));
    }
 
    /** 兜底:不把堆栈泄露给前端,只在服务端日志里保留 */
    @ExceptionHandler(Exception.class)
    public ResponseEntity<Result<Void>> handleOther(Exception e) {
        log.error("未处理异常", e);
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body(Result.error(500, "服务器内部错误: " + e.getClass().getSimpleName()));
    }
}