| | |
| | | |
| | | 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 |
| | |
| | | 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) { |
| | | e.printStackTrace(); |
| | | 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(); |
| | | } |
| | | |