From 588086db8c1844aed41d91787b3509c72cba76d6 Mon Sep 17 00:00:00 2001 From: Nathaniel McCallum Date: Fri, 1 Apr 2022 17:25:50 -0400 Subject: [PATCH] feat: add response::Error This type makes for efficient use of the `?` operator when in a function with multiple return error types that all implement `IntoResponse`. Signed-off-by: Nathaniel McCallum --- axum-core/src/response/error.rs | 26 ++++++++++++++++++++++++++ axum-core/src/response/mod.rs | 3 +++ 2 files changed, 29 insertions(+) create mode 100644 axum-core/src/response/error.rs diff --git a/axum-core/src/response/error.rs b/axum-core/src/response/error.rs new file mode 100644 index 00000000000..50257a8d7e2 --- /dev/null +++ b/axum-core/src/response/error.rs @@ -0,0 +1,26 @@ +use super::{IntoResponse, Response}; + +/// An [IntoResponse]-based error type +/// +/// All types which implement [IntoResponse] can be converted to an [Error]. +/// This makes it useful as a general error type for functions which combine +/// multiple distinct error types but all of which implement [IntoResponse]. +#[derive(Debug)] +pub struct Error(Response); + +impl From for Error { + #[inline] + fn from(value: T) -> Self { + Self(value.into_response()) + } +} + +impl IntoResponse for Result { + #[inline] + fn into_response(self) -> Response { + match self { + Ok(ok) => ok.into_response(), + Err(err) => err.0, + } + } +} diff --git a/axum-core/src/response/mod.rs b/axum-core/src/response/mod.rs index 687743fe825..d41485eac0d 100644 --- a/axum-core/src/response/mod.rs +++ b/axum-core/src/response/mod.rs @@ -9,7 +9,10 @@ use crate::body::BoxBody; mod into_response; mod into_response_parts; +mod error; + pub use self::{ + error::Error, into_response::IntoResponse, into_response_parts::{IntoResponseParts, ResponseParts, TryIntoHeaderError}, };