huang
6 天以前 9571229a2013472dc701ecf5767f2873b36d8f90
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
package com.mes.exception;
 
import com.mes.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.HttpMediaTypeNotAcceptableException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
 
import javax.servlet.http.HttpServletRequest;
 
/**
 * @author zhoush
 * @Date 2024/1/26 15:31
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    /**
     * 如果是serviceExcaption,则调用该方法
     */
    @ExceptionHandler(ServiceException.class)
    @ResponseBody
    public Result handle(ServiceException se) {
        return Result.error(se.getCode(), se.getMessage());
    }
 
    /**
     * 处理媒体类型不匹配异常(通常发生在SSE连接已关闭时)
     */
    @ExceptionHandler(HttpMediaTypeNotAcceptableException.class)
    @ResponseStatus(HttpStatus.NOT_ACCEPTABLE)
    @ResponseBody
    public Result<Object> handleMediaTypeNotAcceptable(HttpMediaTypeNotAcceptableException e, HttpServletRequest request) {
        // 如果是SSE请求,静默处理,不记录错误
        String acceptHeader = request.getHeader("Accept");
        if (acceptHeader != null && acceptHeader.contains("text/event-stream")) {
            log.debug("SSE连接已关闭,忽略媒体类型异常: {}", e.getMessage());
            return null; // 返回null,不写入响应
        }
        log.warn("媒体类型不匹配: {}", e.getMessage());
        return Result.error();
    }
 
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result<Object> error(Exception e, HttpServletRequest request) {
        // 如果是SSE请求且是媒体类型异常,静默处理
        if (e instanceof HttpMediaTypeNotAcceptableException) {
            String acceptHeader = request.getHeader("Accept");
            if (acceptHeader != null && acceptHeader.contains("text/event-stream")) {
                log.debug("SSE连接已关闭,忽略异常: {}", e.getMessage());
                return null;
            }
        }
        log.error("全局异常处理: ", e);
        return Result.error();
    }
 
}