Error handling while using STOMP simple broker

2019-08-16 23:03发布

I am creating simple STOMP broker using @EnableWebSocketMessageBroker. When RuntimeException happens in @MessageMapping method I would like to receive STOMP ERROR frame, but it doesn't work like that by default.

It seems that ERROR frame is not supported in simple broker: https://github.com/spring-projects/spring-framework/blob/master/spring-messaging/src/main/java/org/springframework/messaging/simp/SimpMessageType.java#L28-L44

On the other hand, there is a mechanism to send ERROR frames already available in spring-websocket and its code references some classes which are related to simple broker: https://github.com/spring-projects/spring-framework/blob/master/spring-websocket/src/main/java/org/springframework/web/socket/messaging/StompSubProtocolHandler.java#L349

How to enable mechanism of sending ERROR frames when RuntimeException happens in @MessageMapping method?

1条回答
家丑人穷心不美
2楼-- · 2019-08-16 23:43

Quick and easy way to do this is to have a specific error handler subscription on the client that subsribes before making any calls to the @MessageMapping endpoints. Then wrap all calls to the method in your websocket server with a try catch block and handle the exceptions that occur. Then its a simple case of doing something like:

messagingTemplate.convertAndSend( "/topic/clientControl/1234", "SHUT_DOWN"); (or send to user etc, depends on your subscription model)

You can either send an error message to the client and allow it to handle it or decide what to do server side and have a control subscription allowing the server to pass commands to the client.

查看更多
登录 后发表回答