Search code examples
javaspringspring-mvcspring-websocketspring-restcontroller

Websocket STOMP (or REST) Controller in Spring: capture deserialization error?


I have a Spring Websocket Stomp controller that handles SEND messages (similarly to https://spring.io/guides/gs/messaging-stomp-websocket/) :

@MessageMapping("/pong")
public void handlePong(IncomingModel model) {...} 

It works fine if my IncomingModel can be deserializes behind-the-scenes correctly.

If it is however not the case, I receive something like

2017-02-21 11:24:31.935 ERROR 12536 --- [nboundChannel-3] .WebSocketAnnotationMethodMessageHandler :
Unhandled exception from message handler method
org.springframework.messaging.converter.MessageConversionException:
Could not read JSON: Can not deserialize value of type java.lang.Long from String "2017-02-21T09:24:31.917Z": not a valid Long value

How I can capture this error in my code and handle it? I suppose the case is the same as with REST controllers.


Solution

  • You can put @MessageExceptionHandler(MessageConversionException.class) annotation on method to handle MessageConversionException. Or annotation @MessageExceptionHandler() without parameters to handle any exception.