Replies and error frames
What a message's return type answers — no frame, a reply, or an error frame whose type decides what the client reads — and three handler shapes.
A message answers on the event it was sent on, in the same envelope, and its handler’s return type decides how: no frame, one reply, or an error frame whose type decides what the client may read.
The return contract
Section titled “The return contract”The handler’s return type picks the reply behavior, read by the type itself:
| Return type | Wire effect |
|---|---|
() | No reply frame. Fire-and-forget. |
T | One frame: {"event":"<event>","data":<T serialized>}. |
Result<(), E> | Ok(()) → silent. Err(e) → error frame (see below). |
Result<T, E> | Ok(t) → reply with t. Err(e) → error frame. |
The error frame is shaped like any other envelope:
{ "event": "send", "data": { "error": "text must not be empty" } }What it says is decided by the error’s type, so a client reads only what someone meant it to read:
- a
WsErroris sent whole —WsError::new("text must not be empty"), or aStringthrough?into aResult<T, WsError>; - an error implementing
ToProblemanswers the problem it says: its sentence, and its code beside it ("code": "CONFLICT", plustypeandtitlewhen it names a problem type of its own,retryAfterSecondswhen it names a wait anderrorswhen it carries a field map);ServiceErroris one; - the framework’s own vocabulary found in the chain — a
Problem, a pipe rejection, a decode failure said without its value (invalid type: a string, expected u64 at line 1 column 24) — answers in its own form, a decode failure undercode: "INVALID_ARGUMENT"as a payload or an envelope that does not decode does; - anything else answers
"internal error"undercode: "INTERNAL", and its whole chain is filed once aterroronnest_rs::ws.
That opaque frame is one shape whoever answered it — an unknown error, a
ToProblem saying None, .opaque(), a panic, a request-scoped provider the
message cannot reach:
{ "event": "send", "data": { "error": "internal error", "code": "INTERNAL" } }Every error frame the framework writes says its class in data.code, beside
error, with what a client acts on next to it: reason and requiredScopes
for a guard’s denial, retryAfterSeconds for a wait. A frame a handler builds
itself with WsError::new carries no class, as a GraphQL Error::new carries
none.
A rejection that carries structured detail adds an errors member beside
its class — a payload breaking its type’s rules names the offending fields,
the same way the HTTP body does:
{ "event": "validated", "data": { "error": "invalid payload for `validated`: validation failed", "code": "INVALID_ARGUMENT", "errors": { "text": [{ "code": "length", "message": "text must not be empty" }] } }}errors is the field map and nothing else, on every edge: the class a client
branches on is data.code, as HTTP’s problem document carries code beside
its errors. A pipe’s rejection with no field map is its sentence and
"code": "INVALID_ARGUMENT" alone.
Each entry is { code }, with a message when the #[validate] rule sets
one. A rule’s parameters never ride along — they can hold the rejected
value, so a too-short password never rides back out — and a client keys
its sentence on code.
errors is absent, not null, when the failure had nothing structured to
say, so a client can branch on its presence. Every refused dispatch files its
ws.message line outcome="error", so a denied dispatch shows up in logs
without extra instrumentation, and says why beside it. What the gateway refuses
of what the client sent — a frame that is no envelope, a payload that does not
deserialize, a pipe rejection, an unknown event — is reported at debug on
nest_rs::ws, where it failed included: a client can send one per frame, and
none is a denial. A handler’s Err answered as a refusal — its WsError, a
4xx problem, a pipe rejection, a decode failure — is the client’s error too.
The message’s line files it, with nothing beside it, as HTTP files a 4xx on
its access line alone. A guard’s denial is filed at warn on the guard’s
target, nest_rs::layers when it declares none. An opaque failure is filed at error on nest_rs::ws
(websocket message failed), as is the chain behind a 5xx problem. The
chain behind a 503, the server unable to answer in time, is filed at warn
(websocket message unavailable). Both name the message by the gateway’s
path and its event, as its mounted line does. A handler’s Err is filed
once its answer is final, by the status that answer says, whoever gave it: an
exception filter that answers it as a
refusal files nothing, and one answering a 5xx files the chain it withholds.
A type alias over Result behaves the same. pub type ServiceResult<T> = Result<T, MyError> produces the identical error frame and the identical
line: the decision is made on the type, so however the return is spelled,
an Err never reaches the reply data.
Three handler patterns
Section titled “Three handler patterns”Fire-and-forget — record state, broadcast a derived event later, no reply to the sender:
#[subscribe_message("typing")]async fn typing(&self, msg: SendMessageDto, client: &WsClient) -> Result<(), WsError> { client.broadcast("typing", &msg).opaque()?; Ok(())}The handler answers Ok(()), so no envelope flows back to the sender on
this event. The client.broadcast(...) call pushes a server→client
event on a different event name — see Rooms.
Request/response — the client asks, the server answers on the same event:
#[subscribe_message("presence")]async fn presence(&self) -> usize { self.svc.present()}> {"event":"presence","data":null}< {"event":"presence","data":1}The return value is serialized straight into data. Clients
correlate by event name; if you need multiple in-flight requests of the
same kind, include an id field in the payload and echo it in the
response.
Explicit failure — the operation can fail and the client needs to
see why, so the error says what the client may read through ToProblem:
use nest_rs::core::{Problem, ToProblem, code};
#[derive(thiserror::Error, Debug)]enum SendError { #[error("text must not be empty")] Empty, #[error("rate limited")] RateLimit,}
impl ToProblem for SendError { fn to_problem(&self) -> Option<Problem> { Some(match self { Self::Empty => Problem::new(422, code::INVALID_ARGUMENT) .with_detail("text must not be empty"), Self::RateLimit => Problem::new(429, code::RATE_LIMITED), }) }}
#[subscribe_message("send")]async fn send(&self, msg: SendMessageDto) -> Result<ChatMessageDto, SendError> { if msg.text.is_empty() { return Err(SendError::Empty); } Ok(self.svc.record(msg))}> {"event":"send","data":{"text":""}}< {"event":"send","data":{"error":"text must not be empty","code":"INVALID_ARGUMENT"}}Without the ToProblem impl the same Err answers "internal error" under
code: "INTERNAL": an error’s Display is never what decides. The wire shape stays the same
envelope — clients branch on the presence of data.error, on data.code for
the class, and read the field entries under data.errors when they need to
point at a field.
Going further
Section titled “Going further”- Messages — the envelope, the handler’s signature and the payload it decodes.
- GraphQL errors — the same
ToProblemand.opaque(), answered as a GraphQL error. - Rooms — the frames a handler pushes to other clients.