axum-anyhow 0.1.1

Ergonomic error handling for Axum using anyhow
Documentation
axum-anyhow-0.1.1 has been yanked.

axum-anyhow

A library for ergonomic error handling in Axum applications using anyhow.

This crate provides extension traits and utilities to easily convert Result and Option types into HTTP error responses with proper status codes, titles, and details.

Features

  • Convert anyhow::Result to API errors with custom HTTP status codes
  • Convert Option to API errors when None is encountered
  • Helper functions for common HTTP error codes (400, 401, 403, 404, 500)
  • Automatic JSON serialization of error responses
  • Seamless integration with Axum's IntoResponse trait

Example

use axum::{routing::get, Json, Router};
use axum_anyhow::{ApiResult, ResultExt, OptionExt};
use anyhow::{anyhow, Result};

#[derive(serde::Serialize)]
struct User {
    id: u32,
    name: String,
}

async fn get_user(id: u32) -> ApiResult<Json<User>> {
    // Convert Result errors to 400 Bad Request
    let user_data = fetch_user(id)
        .context_bad_request("Invalid User", "User data is invalid")?;
    
    // Convert Option::None to 404 Not Found
    let user = parse_user(user_data)
        .ok_or_not_found("User Not Found", "No user with that ID")?;
    
    Ok(Json(user))
}

fn fetch_user(id: u32) -> Result<String> {
    // ... implementation
#   Ok("user data".to_string())
}

fn parse_user(data: String) -> Option<User> {
    // ... implementation
#   Some(User { id: 1, name: "Alice".to_string() })
}