Skip to content

Commit 0e6e1b1

Browse files
committed
handle TEXT_EVENT_STREAM_VALUE type
1 parent 96b8042 commit 0e6e1b1

File tree

2 files changed

+16
-1
lines changed

2 files changed

+16
-1
lines changed

src/main/java/cn/netbuffer/springboot/demo/controller/CustomControllerAdvice.java

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,9 @@
22

33
import lombok.extern.slf4j.Slf4j;
44
import org.springframework.http.HttpMethod;
5+
import org.springframework.http.HttpStatus;
6+
import org.springframework.http.MediaType;
7+
import org.springframework.http.ResponseEntity;
58
import org.springframework.web.bind.annotation.ControllerAdvice;
69
import org.springframework.web.bind.annotation.ExceptionHandler;
710
import org.springframework.web.bind.annotation.ResponseBody;
@@ -23,6 +26,15 @@ public Object handleAllException(Exception e, HandlerMethod handlerMethod, HttpM
2326
data.put("status", false);
2427
data.put("msg", e.getMessage());
2528
data.put("processed-by", this.getClass().getSimpleName());
29+
String accept = httpServletRequest.getHeader("Accept");
30+
if (accept != null && accept.contains(MediaType.TEXT_EVENT_STREAM_VALUE)) {
31+
// 对 SSE 请求,返回空或特定 SseEmitter 处理
32+
log.error("SSE request error:{}", e.getMessage());
33+
return ResponseEntity
34+
.status(HttpStatus.INTERNAL_SERVER_ERROR)
35+
.contentType(MediaType.TEXT_PLAIN)
36+
.body(e.getMessage());
37+
}
2638
return data;
2739
}
2840

src/main/java/cn/netbuffer/springboot/demo/controller/SSEController.java

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,10 @@ public SseEmitter handle(String id) {
5555
@GetMapping("sendById")
5656
public void sendById(String id, String message) throws IOException {
5757
log.debug("send message with SseEmitter id={}", id);
58-
sseEmitterMap.get(id).send(message);
58+
SseEmitter emitter = sseEmitterMap.get(id);
59+
if (emitter != null) {
60+
emitter.send(SseEmitter.event().data(message));
61+
}
5962
}
6063

6164
}

0 commit comments

Comments
 (0)