How to send ERROR message to STOMP clients with Spring WebSocket?

孤者浪人 提交于 2019-12-03 05:44:42

You can't just throw exception from the MySubscriptionInterceptor on the clientInboundChannel, because the last one is ExecutorSubscribableChannel, therefore is async and any exceptions from those threads are end up in the logs with any re-throw to the caller - StompSubProtocolHandler.handleMessageFromClient.

But what you can do there is something like clientOutboundChannel and use it like this:

StompHeaderAccessor headerAccessor = StompHeaderAccessor.create(StompCommand.ERROR);
headerAccessor.setMessage(error.getMessage());

clientOutboundChannel.send(MessageBuilder.createMessage(new byte[0], headerAccessor.getMessageHeaders()));

Another option to consider is Annotation mapping:

    @SubscribeMapping("/foo")
    public void handleWithError() {
        throw new IllegalArgumentException("Bad input");
    }

    @MessageExceptionHandler
    @SendToUser("/queue/error")
    public String handleException(IllegalArgumentException ex) {
        return "Got error: " + ex.getMessage();
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!