В моем случае я хочу обработать ошибку, когда проект не был найден на стороне сервера, и отправить событие с сообщением об ошибке.
Моя первая идея заключалась в том, чтобы вызвать исключение из метода службы, а затем обработать его через @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);
}
Код: Выделить всё
Received error
Event { type: 'error', status: 500, message: '' }
Код моего клиента 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()
}
Подробнее здесь: https://stackoverflow.com/questions/701 ... sse-client
Мобильная версия