Kest

Search

Search the documentation

WebSockets

Exception filters

Shape the error a client receives.

When a message handler throws, the gateway answers the sender for you:

What was thrownThe client receives
an HttpException (ForbiddenException, BadRequestException...){"event":"exception","data":{"status":403,"message":"..."}}
something unexpected{"event":"exception","data":{"status":500,"message":"Internal server error"}}, and the real error is logged and sent to error monitoring
an unknown event name{"event":"error","data":{"message":"Unknown event 'x'"}}
text that is not JSON, or has no event{"event":"error","data":{"message":"..."}}

The details of an unexpected error never reach the client. Throw the same HTTP exceptions you use in controllers so one vocabulary covers every entry point:

@SubscribeMessage("kick")
fun kick(client: WsClient, userId: String) {
    if ("ADMIN" !in client.attributes["roles"] as Set<*>) throw ForbiddenException("admins only")     // the sender receives status 403
    ...
}

Business problems that are normal (a name already taken) are often better as a normal reply message than as an exception:

@SubscribeMessage("rename") fun rename(client: WsClient, name: String): Map<String, Any> =
    if (names.tryClaim(name)) mapOf("ok" to true) else mapOf("ok" to false, "reason" to "taken")     // the acknowledgement

Exception filters (@Catch, @UseFilters) use the same pipeline for WebSockets, with fewer WebSocket-specific tests than HTTP.

Read more