Skip to content

Commit

Permalink
feat: add response::{Error, Result}
Browse files Browse the repository at this point in the history
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 <nathaniel@profian.com>
  • Loading branch information
npmccallum committed Apr 8, 2022
1 parent 01a4c88 commit 0278b9a
Showing 1 changed file with 49 additions and 0 deletions.
49 changes: 49 additions & 0 deletions axum-core/src/response/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,52 @@ pub use self::{
/// Type alias for [`http::Response`] whose body type defaults to [`BoxBody`], the most common body
/// type used with axum.
pub type Response<T = BoxBody> = http::Response<T>;

/// A flexible [IntoResponse]-based result 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].
///
/// For example, note that the error types below differ. However, both can be
/// used with the [Result], and therefore the `?` operator, since they both
/// implement [IntoResponse].
///
/// ```no_run
/// use axum_core::response::{IntoResponse, Response, Result};
/// use http::StatusCode;
///
/// fn foo() -> Result<&'static str> {
/// Err((StatusCode::NOT_FOUND, "not found"))?;
/// Err(StatusCode::BAD_REQUEST)?;
/// Ok("ok")
/// }
///
/// fn main() {
/// let response: Response = foo().into_response();
/// }
/// ```
pub type Result<T> = std::result::Result<T, Error>;

impl<T: IntoResponse> IntoResponse for Result<T> {
#[inline]
fn into_response(self) -> Response {
match self {
Ok(ok) => ok.into_response(),
Err(err) => err.0,
}
}
}

/// An [IntoResponse]-based error type
///
/// See [Result] for more details.
#[derive(Debug)]
pub struct Error(Response);

impl<T: IntoResponse> From<T> for Error {
#[inline]
fn from(value: T) -> Self {
Self(value.into_response())
}
}

0 comments on commit 0278b9a

Please sign in to comment.