Video in progress

If an exception is thrown in a @MessageMapping method, how does the client find out?

By default there is no reply at all: the exception is logged and the client stays silent. To return the error to the client, use @MessageExceptionHandler and @SendToUser("/queue/errors"), and the client subscribes to that queue.

📖 Answer

In REST an exception turns into a 4xx/5xx. In STOMP there's no mandatory notion of a "response": the client did SEND and that's it. If the controller throws IllegalArgumentException, the user presses a button and sees that nothing happened.

@Controller
public class BidController {

    @MessageMapping("/auction.bid")
    public void bid(BidRequest req, Principal user) {
        auctionService.placeBid(req, user.getName()); // may throw InsufficientFundsException
    }

    @MessageExceptionHandler(InsufficientFundsException.class)
    @SendToUser(destinations = "/queue/errors", broadcast = false)
    public ErrorDto onNoMoney(InsufficientFundsException ex) {
        return new ErrorDto("NO_FUNDS", "Balans yetarli emas");
    }
}

broadcast = false: the error goes only to the session the request came from, not to the user's other tabs.

If you need a handler shared by all controllers, you can write @MessageExceptionHandler in a @ControllerAdvice class.

So the client knows which error belongs to which request, I usually add a requestId to the payload and return it in the error reply. Without it, several parallel actions get mixed up.

Connection-level errors (for example a bad token in CONNECT) work differently: the client gets a STOMP ERROR frame and the connection is closed. In Spring you can customize that frame through StompSubProtocolErrorHandler.