Skip to content

Error handling

Map errors to responses — defaults on the error type via ToProblem, and typed or catch-all exception filters at the route, the controller or the whole app.

Two seams turn a handler’s error into a response, in the order the framework tries them:

  1. An exception filter — a layer that catches one error type, or every error, at the route, the controller or the whole app, closest first.
  2. ToProblem on a feature’s error type — the default mapping every edge answers with when no filter answered. Lives next to the error in the crate that owns it.

ExceptionFilter is a Layer sub-trait in nest_rs::core, edge-neutral like interceptors: it reads the unit through its execution context, and dedups by TypeId across the global, host and method scopes.

nest_rs::core::ExceptionFilter
#[async_trait]
pub trait ExceptionFilter: Layer {
/// The error it catches, found anywhere in the failure's source chain —
/// `dyn Error + Send + Sync` for every one.
type Exception: Catch + ?Sized;
async fn catch(&self, exception: &Self::Exception, cx: &mut UnitContext<'_>) -> Caught;
}
Terminal window
cargo add nest-rs

The trait, its specs and Caught live in nest_rs::core, which every build has: no feature turns them on.

The default: framework error types, already mapped

Section titled “The default: framework error types, already mapped”

The plumbing failures every service runs into — database errors, input validation, authentication, OAuth wire codes — ship as framework types with their HTTP mapping already wired:

ErrorSourceMaps to
RepoError, through ? into ServiceErrornest_rs::seaorm409 for a unique violation, 403 for a write the caller’s grants do not cover, 404 for a row a write found gone, 503 for a statement cancelled at its bound, else 500 (code: INTERNAL, no detail)
ServiceError::Validation(ValidationErrors)nest_rs::seaorm400, as the edge’s own check of the value answers
AuthError::*nest_rs::authn401 + WWW-Authenticate: Bearer
AuthError::Unavailablenest_rs::authn503, a Retry-After when the failing party gave one — an outage is not a credential signal
CredentialErrornest_rs::authn401 (opaque "invalid credentials")
SignErrornest_rs::authn500 (code: INTERNAL, no detail) — a token this server could not mint says nothing of its caller
TokenError::*nest_rs::oauth::serverRFC 6749 wire codes (400 / 401, the 401 with the Basic challenge of a client refused over HTTP Basic); server_error at 500, or 503 for a dependency that did not answer. ClientAuthenticationGuard and AccessTokenRequest refuse in the same words, the guard at the guard stage, which no filter sees

A service returns the framework type directly; ? flows it to the boundary; the impl decides status and body. What a 5xx among them keeps from the client — the database’s error, the store that did not answer — is filed by the edge, never by the type as it renders: once the answer is final, at error, at warn behind a 503, on nest_rs::http. Every row above converts into nest_rs::http::HttpError — ServiceError through its ToProblem, the authentication and OAuth errors through their own ResponseError — which is what makes the ? legal: a handler returning Result<Json<T>> propagates any of them with no map_err. No per-feature error.rs for these — the framework owns them once, every feature reuses them.

crates/features/src/users/service.rs
use nest_rs::seaorm::{Creatable, ServiceError};
use nest_rs::http::Json;
impl UsersService {
pub async fn create(&self, input: CreateUser) -> Result<User, ServiceError> {
let row = self.create_from_active(active_for_new_user(input)).await?; // → ServiceError::Conflict on a taken email
Ok(User::from(&row))
}
}
#[post("/")]
async fn create(&self, Json(input): Json<CreateUser>)
-> Result<Json<User>, ServiceError>
{
Ok(Json(self.svc.create(input).await?))
}

Write a per-feature error only when the failure is genuinely domain-specific — a wire contract a consumer reads, a security-critical opaque variant. In that case the type lives in <feature>/error.rs and its nest_rs::core::ToProblem impl sits next to it, with no edge’s feature to turn on. Most features never need this — they compose the framework’s types.

ToProblem is every edge’s seam, written once: the Problem it says — a status, a Code, a problem type and its title, a detail, a field map — is what HTTP, GraphQL, WebSockets and MCP answer, each in its own form (see HTTP errors and GraphQL errors). A route, a resolver, a gateway handler or an MCP tool returning the error is read by its type; a body answering the edge’s own error converts it — with ? on HTTP, where every ToProblem error is a ResponseError, and with that edge’s problem_error on GraphQL and MCP (nest_rs::graphql::problem_error, nest_rs::mcp::problem_error). nest_rs::http::ResponseError is for an answer that is no problem document — another protocol’s body, a challenge. What no seam answers — no ToProblem, no ResponseError, no framework type in its chain — is answered opaquely on every edge, and its whole chain is filed once at error, as is the chain behind a 5xx problem or a 5xx a ResponseError answers: a failed handler is never logged nowhere.

When the answer should depend on the concrete error type — DomainError becomes 422, every other failure keeps its own answer — write an exception filter. It names the type it claims in Exception; a failure whose chain does not carry that type never reaches it, and one that does gets the filter’s catch:

apps/api/src/exception_filter.rs
use nest_rs::core::{
Caught, ExceptionFilter, Layer, Problem, ToProblem, UnitContext, async_trait, injectable,
};
use nest_rs::http::{HttpView, IntoResponse, ProblemDetails};
#[derive(Debug, thiserror::Error)]
#[error("domain failure: {0}")]
pub struct DomainError(pub String);
impl ToProblem for DomainError {
fn to_problem(&self) -> Option<Problem> {
None
}
}
#[injectable]
#[derive(Layer)]
pub struct DomainErrorFilter;
#[async_trait]
impl ExceptionFilter for DomainErrorFilter {
type Exception = DomainError;
async fn catch(&self, err: &DomainError, cx: &mut UnitContext<'_>) -> Caught {
let problem = ProblemDetails::unprocessable().with_detail(format!("caught: {err}"));
match HttpView::of(cx) {
Ok(view) => Caught::Answered(view.respond(problem.into_response())),
Err(_) => Caught::Declined,
}
}
}

catch answers one of three ways:

CaughtWhat the client reads
Answered(settled)the reply the filter wrote through the edge’s view
Problem(problem)a nest_rs::core::Problem, which every edge renders in its own form — the problem document on HTTP
Declinedwhatever the next filter answers, else the default

The ToProblem impl is what lets a route return DomainError; the problem it says is the default the filter replaces, here none. Drop the filter and the same handler answers the opaque 500 — code: INTERNAL, no detail.

A filter reads the request it answers through the same view, view.request() in the match above — its method, its headers, its extensions — so it can answer in the media type the client accepts; only the body is gone once the handler read it. What the client is finally sent decides what is filed, whatever the failure’s type: a failure a filter answers with a 4xx files nothing, and one it answers with a 5xx, its own reply or a Problem, files the chain the client is not told once, at error, at warn behind a 503. Drop the filter above, and DomainError’s default 500 files domain failure: boom the same way.

Bind it like any other layer: for the whole app with GlobalExceptionFilters<(DomainErrorFilter,)> in the providers of the module the app boots, on a controller with #[use_exception_filters(DomainErrorFilter)], or beside a verb:

crates/features/src/users/http/controller.rs
#[get("/domain")]
#[use_exception_filters(DomainErrorFilter)]
async fn domain(&self) -> Result<&'static str, DomainError> {
Err(DomainError("boom".into()))
}

That answers 422 with caught: domain failure: boom.

A resolver binds filters as a controller does — #[use_exception_filters] on the #[resolver] struct or beside a root field — and a filter answers a field with a Problem, rendered in GraphQL’s own form: an exception filter answers first.

type Exception = dyn Error + Send + Sync claims every failure — the envelope a product answers every error in. Bound globally, it also shapes what no route answers: a 404 for a path nothing serves, a 405 for a method a path does not take, an API version the header or media-type strategy refuses, and a self-mount’s own error, such as /graphql refusing an oversized batch. A pipe’s refusal is one of them: its RFC 9457 400 (validation at the edge) answers in your API’s own envelope ({ ok: false, error: { ... } }) through one catch-all bound globally, and the error itself stays pure.

#[async_trait]
impl ExceptionFilter for Envelope {
type Exception = dyn std::error::Error + Send + Sync;
async fn catch(&self, _: &Self::Exception, cx: &mut UnitContext<'_>) -> Caught {
/* answer every failure in the product's own envelope */
Caught::Declined
}
}

The method’s filters are tried first, then the controller’s — or the resolver’s — then the app’s; the first that answers wins. A typed filter on a route therefore answers before a catch-all on its controller, and a Declined hands the failure on.

A filter changes what the client reads, never whether the unit failed: a mutating request whose handler failed rolls its writes back, whatever status the filter answered — a 200 included. A guard’s refusal never reaches a filter: it is answered by the guard stage, before the filters run.

An exception filter declared globally and redeclared on a controller or a method runs once, at the broadest scope that declares it — the same defense-in-depth rationale as guards: a portable controller that needs a domain filter redeclares it, and the dedup keeps the cost at zero.

Exception filters run around the handler stage, after the guards and the posture’s class gate, so a failure of the handler or of any handler-stage interceptor reaches them. The full order is on the request lifecycle.

SeamWhere it livesWhen to reach for it
ToProblem on an error typeFramework crate that owns the error (nest-rs-seaorm), or <feature>/error.rs for a domain-specific variantDefault. Every handler returning that error gets the same mapping, on every edge
A typed ExceptionFilterA providerThe mapping depends on the error type across many routes
A catch-all ExceptionFilterA providerOne envelope for every failure, bound on a route, a controller or the app

Reach for ToProblem first.