Axum response codes

Simplifying error handling in Axum with Rust macros

Josh Nies's avatar
Josh Nies
Aug 23, 2024
∙ Paid
1
Share
text
Photo by David Pupăză on Unsplash

During the development of Vela's Rust backend, I've become acutely cognizant of the verbosity inherent in Axum's error handling mechanisms. This prolixity not only proves to be time-consuming but also diminishes some of the inherent pleasure derived from writing Rust code. The repetitive nature of error handling can often detract from the elegance and efficiency that Rust typically offers.

To mitigate this issue and streamline the development process, I went ahead and created a collection of dead-simple macros to streamline Axum’s error handling. After spending several hours refactoring each route in Vela’s codebase, I have to say: Rust macros are pretty sweet.

A typically endpoint went from this:

pub async fn endpoint(...) -> Result<..., (StatusCode, Json<ErrorResponse>)> {
    ...
	
    if ... {
        return Err(
            StatusCode::BAD_REQUEST,
	    Json(ErrorResponse(
                error: "Hey, don't do that"
	    ))
	);
    }
	
    ...
}

To this:

pub async fn endpoint(...) -> Result<..., (StatusCode, Json<ErrorResponse>)> {
    ...
	
    if ... {
        bad_request!("Hey, don't do that");
    }
	
    ...
}

Keep reading with a 7-day free trial

Subscribe to Shades of Vivian to keep reading this post and get 7 days of free access to the full post archives.

Already a paid subscriber? Sign in
© 2025 Joshua Nies
Privacy ∙ Terms ∙ Collection notice
Start writingGet the app
Substack is the home for great culture