rama::http::layer

Module error_handling

Expand description

Middleware to turn Service errors into Responses.

§Example

use rama_core::{
    service::service_fn,
    Context, Service, Layer,
};
use rama_http::{
    service::client::HttpClientExt,
    layer::{error_handling::ErrorHandlerLayer, timeout::TimeoutLayer},
    service::web::WebService,
    Body, IntoResponse, Request, Response, StatusCode,
};
use std::time::Duration;


async fn handler<S>(_ctx: Context<S>, _req: Request) -> Result<Response, std::io::Error> {
    some_expensive_io_operation().await?;
    Ok(StatusCode::OK.into_response())
}

    let home_handler = (
        ErrorHandlerLayer::new().error_mapper(|err| {
            tracing::error!("Error: {:?}", err);
            StatusCode::INTERNAL_SERVER_ERROR.into_response()
        }),
        TimeoutLayer::new(Duration::from_secs(5)),
        ).layer(service_fn(handler));

    let service = WebService::default().get("/", home_handler);

    let _ = service.serve(Context::default(), Request::builder()
        .method("GET")
        .uri("/")
        .body(Body::empty())
        .unwrap()).await;

Structs§