Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add response::ErrorResponse and response::Result #921

Merged
merged 8 commits into from
Apr 21, 2022
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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};
davidpdrsn marked this conversation as resolved.
Show resolved Hide resolved
/// 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();
/// }
davidpdrsn marked this conversation as resolved.
Show resolved Hide resolved
/// ```
pub type Result<T> = std::result::Result<T, Error>;
davidpdrsn marked this conversation as resolved.
Show resolved Hide resolved

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.
npmccallum marked this conversation as resolved.
Show resolved Hide resolved
#[derive(Debug)]
pub struct Error(Response);

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