ulo
ulo
Documentation

Start here

Coming from NestJSNestJS topics, mapped

The model

Request LifecycleMiddlewareGuardsInterceptorsError Handling

Protocols

Integrations

Operating

Reference

Request Lifecycle

Error Handling

Classified domain errors, the problem-details body, and the error handlers that can claim, pass on or reshape an error.

One error model serves every transport. A domain error is an error type of your own, such as NoteNotFound below, and says what kind of failure it is. Each transport renders that kind its own way, and error handlers can intercept the error before it is rendered. The examples are examples/15-http-requests (classification and rendering) and examples/16-http-enhancers (error handlers).

Classifying a domain error

An error becomes part of the model by implementing Classify, usually with the derive. #[classify(not_found)] is the whole mapping:

use std::fmt;

use ulo_http::{Classify, Json, Path};

#[derive(Debug, Classify)]
#[classify(not_found)]
pub struct NoteNotFound(pub u32);

impl fmt::Display for NoteNotFound {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "no note {}", self.0)
    }
}

impl std::error::Error for NoteNotFound {}

#[ulo_http::get("/notes/{id}")]
fn find(&self, Path(id): Path<u32>) -> Found {
    let all = self.notes.all.lock().unwrap();
    all.iter().find(|note| note.id == id).cloned().map(Json).ok_or(NoteNotFound(id))
}

A handler returns Result<V, E> for any E that is Classify or converts into a CallError, and the error reaches the error handlers. The spelling of the return type decides nothing. An alias works the same: the Found above is type Found = Result<Json<Note>, NoteNotFound>.

On an enum the attribute goes on each variant, or on the enum as the default for variants without one. A variant with no kind is a compile error.

The eleven kinds and what each renders as:

ErrorKind#[classify(..)]HTTPgRPC
BadRequestbad_request400INVALID_ARGUMENT
Unauthorizedunauthorized401 with WWW-AuthenticateUNAUTHENTICATED
Forbiddenforbidden403PERMISSION_DENIED
NotFoundnot_found404NOT_FOUND
Conflictconflict409ABORTED
Unprocessableunprocessable422INVALID_ARGUMENT with field violations
TooManyRequeststoo_many_requests429, Retry-After from a RetryAfter detailRESOURCE_EXHAUSTED
Timeouttimeout504DEADLINE_EXCEEDED
Unavailableunavailable503, Retry-After when a RetryAfter detail is presentUNAVAILABLE
Unimplementedunimplemented501UNIMPLEMENTED
Internalinternal500INTERNAL

WebSocket and RPC render a kind as an envelope { "kind", "message", "details" }. CallError::new(kind, message) builds an error with no domain type behind it, and CallError::unauthorized(challenge) builds a 401 that carries its own WWW-Authenticate challenge. Without one the response carries the server's default, Bearer unless Server::challenge(..) set another.

An error nothing classified, a plain std::io::Error for example, renders as Internal with its text withheld.

Overriding the status, close code or gRPC code

The kind decides the rendering on every transport. Three extension traits on CallError replace the wire value on one transport and leave the kind, and so every other transport's rendering, unchanged:

  • ulo_http::WithHttpStatus::with_http_status(StatusCode) sets the HTTP status. CallError::new(ErrorKind::Conflict, "the version changed").with_http_status(StatusCode::PRECONDITION_FAILED) answers 412 and is still a Conflict elsewhere. Headers follow the status: a 401 carries WWW-Authenticate, and a 429 or 503 carries Retry-After from a RetryAfter detail. A status outside 400 to 599 is ignored and logged at warn.
  • ulo_ws::WithCloseCode::with_close_code(CloseCode) sets the close code of a refused WebSocket connect. A message handler's error still answers the envelope, whose kind the kind decides.
  • ulo_grpc::WithGrpcCode::with_grpc_code(Code) sets the gRPC status code.

Message and details

Classify has two defaulted methods. public_message() is what the client reads, the error's Display text unless overridden, and details() returns typed Detail entries:

impl Classify for Throttled {
    fn classify(&self) -> ErrorKind {
        ErrorKind::TooManyRequests
    }

    fn public_message(&self) -> Cow<'_, str> {
        Cow::Borrowed("slow down")
    }

    fn details(&self) -> Details {
        Details::new().with(Detail::RetryAfter(Duration::from_millis(1500)))
    }
}

This is from crates/ulo-http/tests/errors.rs. The response is a 429 with Retry-After: 2 (rounded up to whole seconds) and a details entry {"type": "retry_after", "seconds": 2}. The Detail variants are FieldViolations, ErrorInfo, RetryAfter, Help and Json.

The HTTP body is problem details

An HTTP failure is an RFC 9457 document served as application/problem+json:

{
  "type": "about:blank",
  "title": "Not Found",
  "status": 404,
  "detail": "no note 7"
}

title is the status's reason phrase, status the code, and detail the public_message. details, when the error carries any, is an extension member holding the typed entries. A validation failure names the field:

{
  "type": "about:blank",
  "title": "Unprocessable Content",
  "status": 422,
  "detail": "`Json` failed 1 validation rule",
  "details": [{ "type": "field_violations", "violations": [{ "field": "title", "description": "<the rule's message>" }] }]
}

examples/15-http-requests/tests/requests.rs asserts the 404 document, the 422 document and the field name. See Validation for how a rule failure becomes a 422.

Extraction failures are classified too. A body that does not parse is 400, content that parses and does not fit its type is 422, an unsupported media type is 415 with an Accept header naming the one expected, and a body over its limit is 413.

Error handlers

An error handler sees an error before it is rendered. It answers Ok(reply) to claim the error, or Err(error) to pass it on, the same error or a reshaped one.

pub trait ErrorHandler<T: Transport>: Send + Sync + 'static {
    fn handle(&self, err: BoxError, cx: &T::Cx) -> impl Future<Output = Result<T::Reply, BoxError>> + Send;
}

This one answers a guard's refusal in its own words and hands every other error on:

use ulo::{BoxError, Dep, ErrorHandler, GuardRejected, injectable};
use ulo_http::{Http, HttpBody, HttpCx, Response, StatusCode};

#[injectable]
pub struct Refusals {
    trace: Dep<Trace>,
}

impl ErrorHandler<Http> for Refusals {
    async fn handle(&self, err: BoxError, cx: &HttpCx) -> Result<Response, BoxError> {
        let Some(refused) = err.downcast_ref::<GuardRejected>() else { return Err(err) };
        self.trace.push("error handler");
        let needed = cx.exec().handler().and_then(|handler| handler.meta::<RequiresRole>()).map_or("-", |role| role.0);
        let mut reply = Response::new(HttpBody::from(format!("{} needs role {needed}", refused.guard.rsplit("::").next().unwrap_or(refused.guard))));
        *reply.status_mut() = StatusCode::FORBIDDEN;
        Ok(reply)
    }
}

It is declared with #[error_handlers(Refusals)] on the impl, or on a handler, or as an into AnyErrorHandler<Http> entry in the module for the global tier.

What a handler receives

The error is a BoxError. What it holds depends on where the failure happened:

FailureArrives as
a handler's Err(e)e itself, wrapped in a CallError when it is Classify; reach it with call.source_as::<E>()
a guard's Ok(false)GuardRejected { guard }
a panic in a guard, interceptor, handler or error handlerPanicRecovered { stage, message }, the message redacted
a failed extractora CallError whose source is ExtractError
a path no route matchesa CallError of kind NotFound whose source is ulo_http::NoRoute
a known path with another methoda CallError of kind BadRequest whose source is ulo_http::MethodNotAllowed; unclaimed it renders 405 with Allow
a middleware or tower layer Errthe BoxError it returned

CallError::from_boxed(err) recognises all of these and gives a CallError with a kind(). The global handler in examples/16-http-enhancers/src/order.rs uses it to answer one domain error and leave the rest:

impl ErrorHandler<Http> for Shape {
    async fn handle(&self, err: BoxError, _cx: &HttpCx) -> Result<Response, BoxError> {
        let call = CallError::from_boxed(err);
        let Some(OutOfStock(sku)) = call.source_as::<OutOfStock>() else { return Err(Box::new(call)) };
        self.trace.push("global");
        let mut reply = Response::new(HttpBody::from(format!("sku {sku} is sold out")));
        *reply.status_mut() = StatusCode::CONFLICT;
        Ok(reply)
    }
}

ulo::is_panic(&err) answers true for a recovered panic whichever shape it arrives in, so one handler can map every panic to one status.

Order

Handlers are asked method tier first, then controller, then global, and within a tier the last declared first. The first to answer Ok claims the error and the rest never see it. A handler that returns Err hands the next one the error it returned. That lets a handler reshape an error for the tiers after it, or observe one and pass it on unchanged.

order.rs registers Telemetry and Method on one handler, in that order, and a controller and a global handler beside them. For GET /stock/7 the handlers run:

method, telemetry: sku 7 is out of stock, controller, global

Method, declared last, goes first. The global handler answers the 409. A handler that answers ends the search: with #[error_handlers(Telemetry, Claimer)] only claimer runs.

An error no handler claims is rendered by the transport:

  • a GuardRejected renders the transport's forbidden status, 403 on HTTP;
  • a PanicRecovered renders Internal with a generic message, 500 on HTTP;
  • a CallError renders by its kind.

Panics

A panic in a guard, an interceptor, the handler or an error handler is caught at its own stage and offered to the error handlers as PanicRecovered. The next request is served normally. The panic message is redacted before it reaches a handler, and an unclaimed panic renders a 500 that withholds it. The default panic hook prints the raw message to stderr before any of this runs. ulo::panic::install_redacting_hook() in main replaces it with one that prints the message redacted. crates/ulo-http/tests/errors.rs asserts that a handler's panic text never appears in the response and that the app keeps serving.

A panic while the container builds an enhancer or the controller arrives as a lookup error rather than PanicRecovered; is_panic recognises both.

Errors after a stream has started

A streaming reply, SSE included, has sent its status by the time an item can fail, so an Err item cannot change it. Item errors go to the same handlers, with cx.exec().is_late() true:

  • A handler returning Err(e) reshapes the error, and the transport writes it in its mid-stream form: on SSE an event named error whose data is {"kind", "message", "details"}, after which the stream ends.
  • A handler returning Ok(_) is ignored and logged, and the original error is written. Ending cleanly on a failure would tell the client the stream completed.
  • A handler returning Err(EndStream.into()) ends the stream as if it had returned None.

EndStream is ulo::EndStream, a unit struct.

Interceptors

Wrap the handler, run code on both sides of it, or answer in its place.

Extractors

Handler parameters that read the call, checked when the application is built.

On this page

Classifying a domain errorOverriding the status, close code or gRPC codeMessage and detailsThe HTTP body is problem detailsError handlersWhat a handler receivesOrderPanicsErrors after a stream has started