Crate anyhow_http

Source
Expand description

anyhow-http offers customizable HTTP errors built on anyhow errors.

This crates acts as a superset of anyhow, extending the functionality to define custom HTTP error responses.

§Example with axum

use axum::{
   routing::get,
   response::IntoResponse,
   Router,
};
use anyhow_http::{http_error_bail, response::HttpJsonResult};

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/", get(handler));

    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

fn fallible_operation() -> anyhow::Result<()> {
    http_error_bail!(INTERNAL_SERVER_ERROR, "this is an error")
}

async fn handler() -> HttpJsonResult<impl IntoResponse> {
    fallible_operation()?;
    Ok(())
}

Re-exports§

pub use http;

Modules§

derivederive
response
Creating responses from HttpError.

Macros§

http_error
Construct an ad-hoc Error from a status code, optional source error and formatted reason.
http_error_bail
Shorthand macro to return early with an Error.

Structs§

HttpError
HttpError is an error that encapsulates data to generate Http error responses.

Traits§

OptionExt
Extension trait to transform an Option to a HttpError.
ResultExt
Extension trait to map the error variant of a Result to a HttpError.