Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

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

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

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