From f11e2502ddc40ee93daa142a892dcb221f64a2b3 Mon Sep 17 00:00:00 2001 From: Florian Briand Date: Mon, 23 Sep 2024 18:55:31 +0200 Subject: [PATCH] feat: handle axum errors with anyhow --- Cargo.lock | 5 +++-- crates/backend/Cargo.toml | 1 + crates/backend/src/lib.rs | 25 +++++++++++++++++++++++++ 3 files changed, 29 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index d8dda46..39b5b13 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -82,9 +82,9 @@ checksum = "1bec1de6f59aedf83baf9ff929c98f2ad654b97c9510f4e70cf6f661d49fd5b1" [[package]] name = "anyhow" -version = "1.0.86" +version = "1.0.89" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b3d1d046238990b9cf5bcde22a3fb3584ee5cf65fb2765f454ed428c7a0063da" +checksum = "86fdf8605db99b54d3cd748a44c6d04df638eb5dafb219b135d0149bd0db01f6" [[package]] name = "async-broadcast" @@ -334,6 +334,7 @@ dependencies = [ name = "backend" version = "0.1.0" dependencies = [ + "anyhow", "axum", "cargo-watch", "listenfd", diff --git a/crates/backend/Cargo.toml b/crates/backend/Cargo.toml index 4572aa3..8dc8c07 100644 --- a/crates/backend/Cargo.toml +++ b/crates/backend/Cargo.toml @@ -4,6 +4,7 @@ version = "0.1.0" edition = "2021" [dependencies] +anyhow = "1.0.89" axum = "0.7.6" listenfd = "1.0.1" tokio = { version = "1.40.0", features = ["macros", "rt-multi-thread"] } diff --git a/crates/backend/src/lib.rs b/crates/backend/src/lib.rs index f1c0602..530b3dd 100644 --- a/crates/backend/src/lib.rs +++ b/crates/backend/src/lib.rs @@ -1,4 +1,6 @@ +use anyhow::Error as AnyError; use axum::http::{StatusCode, Uri}; +use axum::response::{IntoResponse, Response}; use axum::{routing::get, Router}; pub fn get_router() -> Router { @@ -10,3 +12,26 @@ pub fn get_router() -> Router { async fn fallback(uri: Uri) -> (StatusCode, String) { (StatusCode::NOT_FOUND, format!("No route for {uri}")) } + +struct AppError(AnyError); + +// To automatically convert `AppError` into a response +impl IntoResponse for AppError { + fn into_response(self) -> Response { + ( + StatusCode::INTERNAL_SERVER_ERROR, + format!("Internal Server Error: {}", self.0), + ) + .into_response() + } +} + +// To automatically convert `AnyError` into `AppError` +impl From for AppError +where + E: Into, +{ + fn from(err: E) -> Self { + Self(err.into()) + } +}