【问题标题】:How to handle exception and send error to SSE client如何处理异常并将错误发送到 SSE 客户端
【发布时间】:2022-09-28 22:01:14
【问题描述】:

我正在使用 Spring 的 SseEmitter 实现与 SSE 合作。 就我而言,我想在服务器端找不到项目时处理错误并发送带有错误消息的事件。

我的第一个想法是从 service\ 的方法中抛出一个异常,然后通过 @ExceptionHandler 在用 @ControllerAdvice 注释的类中处理它。这不起作用,因为@ControllerAdvice 类对 SSE 客户端一无所知。

之后我尝试了以下代码:

private void sendError(String message, int status) {
    log.error(\"Processing report {} stopped with error \'{}\", getContextLogMessage(), message);
    sseEmitter.completeWithError(new ApiError(message, HttpStatus.resolve(status)));
    sseEmitter.onCompletion(this::stopSelf); 
}

但通过 SSE 客户端收到下一条消息:

Received error
Event { type: \'error\', status: 500, message: \'\' }

看起来 Spring 的默认错误消息已传递给 SSE 客户端。

我的 SSE 客户的代码:

const EventSource = require(\'eventsource\')
const eventSource = new EventSource(\'http://localhost:8080/testing\')

eventSource.onmessage = (e) => {
  const data = JSON.parse(e.data)
  if (data.status == null) {
    console.log(data)
  } else if (data.status === \'DONE\') {
    console.log(data.status);
    eventSource.close()
  } else {
    console.log(\'status = \' + data.status)
  }
}

eventSource.onerror = (e) => {
  console.log(\'Received error\')
  console.log(e)
  eventSource.close()
}

我的问题是 - 是否存在通过@ExceptionHandler 处理它的可能性?可能是我对 Spring 的 SSE 有什么误解,我之前只用过sseEmitter.send()

    标签: java spring spring-boot exception server-sent-events


    【解决方案1】:

    同样的问题在这里,试图添加评论,但我太新了。

    【讨论】:

    猜你喜欢
    • 2016-10-27
    • 2018-02-10
    • 2015-08-18
    • 1970-01-01
    • 1970-01-01
    • 2019-07-27
    • 2015-04-26
    • 1970-01-01
    • 2019-06-12
    相关资源
    最近更新 更多