ulo
ulo
Documentation

Start here

Coming from NestJSNestJS topics, mapped

The model

Protocols

Integrations

RecipesServe static filesCompress responsesSecurity headers and CSRFSessions with tower-sessionsCookies with tower-cookiesRequest IDsAccess logError reporting with SentryLocalised responses with FluentA client as a providerA MongoDB ODM over the injected clientExplicit transactions with SQLxA mailer over lettreObject storage over the AWS SDKA CLI command with clapMocks with mockallFeature flags with OpenFeatureAuthorization with CedarMoving from axum or actix-web

Operating

Reference

Recipes

Error reporting with Sentry

Report server faults to Sentry with the sentry-tracing error layer, fed by a global ErrorHandler that logs and passes every error on.

A request that fails with a server fault produces one Sentry event, and a deliberate 4xx produces none. The global ErrorHandler sees each error before it renders, logs the faults at error level, and returns Err(err) so the response is unchanged. sentry-tracing's ErrorLayer turns an error event into a Sentry event.

The recipe builds on examples/16-http-enhancers, whose Refusals handler is registered the same way. It compiled and ran on port 0 against sentry 0.49.6 and sentry-tracing 0.49.6, with Sentry's TestTransport standing in for the network, so what reached the client was observed and no event was sent to a server.

sentry = "0.49"
sentry-tracing = "0.49"
tracing = "0.1"
tracing-subscriber = "0.3"

The code

use sentry_tracing::ErrorLayer;
use tracing_subscriber::filter::LevelFilter;
use tracing_subscriber::layer::SubscriberExt;
use tracing_subscriber::util::SubscriberInitExt;
use tracing_subscriber::Layer;
use ulo::{AnyErrorHandler, App, AppBuilder, BoxError, ErrorHandler, controller, handlers, injectable, module};
use ulo_http::{CallError, ErrorKind, Http, HttpCx, Response};

/// Forwards the errors that are server faults to `tracing`, where the Sentry layer turns an
/// `error` event into a Sentry event, and hands every error on unchanged.
#[injectable]
pub struct Report;

impl ErrorHandler<Http> for Report {
    async fn handle(&self, err: BoxError, cx: &HttpCx) -> Result<Response, BoxError> {
        let call = CallError::from_boxed(err);
        if call.kind() == ErrorKind::Internal {
            let cause = std::error::Error::source(&call).map_or_else(|| call.to_string(), ToString::to_string);
            tracing::error!(path = cx.head().parts().uri.path(), error = %cause, "request failed");
        }
        Err(Box::new(call))
    }
}

/// Starts the client and registers the Sentry error layer beside a `fmt` layer on one registry.
/// The guard flushes pending events when it drops, so `main` holds it until the app has closed.
pub fn start(dsn: &str) -> sentry::ClientInitGuard {
    let guard = sentry::init(sentry::ClientOptions::new().dsn(dsn));
    init();
    guard
}

/// The subscriber alone, for a process that starts the Sentry client elsewhere.
pub fn init() {
    tracing_subscriber::registry()
        .with(tracing_subscriber::fmt::layer().with_target(false))
        .with(ErrorLayer::new().with_filter(LevelFilter::ERROR))
        .init();
}

#[controller]
pub struct BillingController;

#[handlers]
impl BillingController {
    #[ulo_http::get("/charge")]
    fn charge(&self) -> Result<&'static str, BoxError> {
        Err("card processor unreachable".into())
    }

    #[ulo_http::get("/missing")]
    fn missing(&self) -> Result<&'static str, BoxError> {
        Err(CallError::new(ErrorKind::NotFound, "no such invoice").into())
    }
}

#[module(
    providers = [Report, into AnyErrorHandler<Http>: [Report]],
    controllers = [BillingController],
)]
pub struct AppModule;

pub fn builder() -> AppBuilder {
    App::builder(AppModule)
}

main holds the guard that start returns until the app has closed:

let _sentry = sentry_errors::start("https://<key>@<org>.ingest.sentry.io/<project>");

What each seam does

CallError::from_boxed(err) recognises every error the stage can carry and gives a CallError with a kind(). A handler's plain Err("..".into()) arrives with kind Internal, and the handler reads the original message through std::error::Error::source, because a CallError displays the redacted internal error. A CallError::new(ErrorKind::NotFound, ..) is a deliberate answer and is not reported.

tracing::error!(path = .., error = %cause, "request failed") runs inside the call span. ErrorLayer::new().with_filter(LevelFilter::ERROR) converts it into a Sentry event, with the fields under the event's Rust Tracing Fields context.

The module registers the handler with into AnyErrorHandler<Http>: [Report] for the global tier, and Report in providers so it exists in the container.

Observed with GET /charge (handler Err) and GET /missing (NotFound):

RequestResponseCaptured by the client
GET /charge500, internal errorone event: level Error, message request failed, fields error: card processor unreachable, path: /charge
GET /missing404, no such invoicenone

Failure modes

sentry_tracing::layer() is deprecated. In 0.49 it warns and points to SpanLayer, LogLayer and ErrorLayer. This recipe uses ErrorLayer alone for issues. SpanLayer adds transactions and needs traces_sample_rate in the client options (read in the crate documentation, not run).

The subscriber must exist before the first request. start registers the layer on the global subscriber. Events emitted before it runs are lost, and a second global subscriber panics.

A panic arrives as PanicRecovered. from_boxed maps it to Internal with a generic message (read in the CallError documentation, not run), so the filter reports a panic like any other fault. See the table in Error handling.

The guard flushes on drop. Events are sent from a background thread. A process that exits without dropping the ClientInitGuard can lose the last events (read in the sentry documentation, not run).

Error fields can carry personal data. error = %cause prints whatever the error's message says. The framework redacts what it renders to the client, and a field written to tracing is not redacted.

Reference

  • Error handling: ErrorHandler, CallError::from_boxed and what each failure arrives as.
  • Logging and tracing: the call span the error event is recorded in.

Access log

One log line per request, with status and duration, from tracing-subscriber span-close events on the call span.

Localised responses with Fluent

Negotiate Accept-Language in an extractor, translate with fluent, and localise the problem document in a global ErrorHandler.

On this page

The codeWhat each seam doesFailure modesReference