Skip to main content

axum_core/response/
mod.rs

1//! Types and traits for generating responses.
2//!
3//! See [`axum::response`] for more details.
4//!
5//! [`axum::response`]: https://docs.rs/axum/0.8/axum/response/index.html
6
7use std::convert::Infallible;
8
9use http::StatusCode;
10
11use crate::body::Body;
12
13mod append_headers;
14mod into_response;
15mod into_response_parts;
16
17pub use self::{
18    append_headers::AppendHeaders,
19    into_response::IntoResponse,
20    into_response_parts::{IntoResponseParts, ResponseParts, TryIntoHeaderError},
21};
22
23/// Type alias for [`http::Response`] whose body type defaults to [`Body`], the most common body
24/// type used with axum.
25pub type Response<T = Body> = http::Response<T>;
26
27/// An [`IntoResponse`]-based result type that uses [`ErrorResponse`] as the error type.
28///
29/// All types which implement [`IntoResponse`] can be converted to an [`ErrorResponse`]. This makes
30/// it useful as a general purpose error type for functions which combine multiple distinct error
31/// types that all implement [`IntoResponse`].
32///
33/// # Example
34///
35/// ```
36/// use axum::{
37///     response::{IntoResponse, Response},
38///     http::StatusCode,
39/// };
40///
41/// // two fallible functions with different error types
42/// fn try_something() -> Result<(), ErrorA> {
43///     // ...
44///     # unimplemented!()
45/// }
46///
47/// fn try_something_else() -> Result<(), ErrorB> {
48///     // ...
49///     # unimplemented!()
50/// }
51///
52/// // each error type implements `IntoResponse`
53/// struct ErrorA;
54///
55/// impl IntoResponse for ErrorA {
56///     fn into_response(self) -> Response {
57///         // ...
58///         # unimplemented!()
59///     }
60/// }
61///
62/// enum ErrorB {
63///     SomethingWentWrong,
64/// }
65///
66/// impl IntoResponse for ErrorB {
67///     fn into_response(self) -> Response {
68///         // ...
69///         # unimplemented!()
70///     }
71/// }
72///
73/// // we can combine them using `axum::response::Result` and still use `?`
74/// async fn handler() -> axum::response::Result<&'static str> {
75///     // the errors are automatically converted to `ErrorResponse`
76///     try_something()?;
77///     try_something_else()?;
78///
79///     Ok("it worked!")
80/// }
81/// ```
82///
83/// # As a replacement for `std::result::Result`
84///
85/// Since `axum::response::Result` has a default error type you only have to specify the `Ok` type:
86///
87/// ```
88/// use axum::{
89///     response::{IntoResponse, Response, Result},
90///     http::StatusCode,
91/// };
92///
93/// // `Result<T>` automatically uses `ErrorResponse` as the error type.
94/// async fn handler() -> Result<&'static str> {
95///     try_something()?;
96///
97///     Ok("it worked!")
98/// }
99///
100/// // You can still specify the error even if you've imported `axum::response::Result`
101/// fn try_something() -> Result<(), StatusCode> {
102///     // ...
103///     # unimplemented!()
104/// }
105/// ```
106pub type Result<T, E = ErrorResponse> = std::result::Result<T, E>;
107
108impl<T> IntoResponse for Result<T>
109where
110    T: IntoResponse,
111{
112    fn into_response(self) -> Response {
113        match self {
114            Ok(ok) => ok.into_response(),
115            Err(err) => err.0,
116        }
117    }
118}
119
120/// An [`IntoResponse`]-based error type
121///
122/// See [`Result`] for more details.
123#[derive(Debug)]
124#[must_use]
125pub struct ErrorResponse(Response);
126
127impl<T> From<T> for ErrorResponse
128where
129    T: IntoResponse,
130{
131    fn from(value: T) -> Self {
132        Self(value.into_response())
133    }
134}
135
136/// Response part that stops status code overrides.
137///
138/// This type should be used by types implementing [`IntoResponseParts`] or
139/// [`IntoResponse`] when they fail to produce the response usually expected of
140/// them and return some sort of error response instead.
141///
142/// It is checked used by the tuple impls of [`IntoResponse`] that have a
143/// [`StatusCode`] as their first element to ignore that status code.
144/// Consider the following example:
145///
146/// ```no_run
147/// # use axum::Json;
148/// # use http::StatusCode;
149/// # #[derive(serde::Serialize)]
150/// # struct CreatedResponse { }
151/// fn my_handler(/* ... */) -> (StatusCode, Json<CreatedResponse>) {
152///     // This response type's serialization may fail
153///     let response = CreatedResponse { /* ... */ };
154///     (StatusCode::CREATED, Json(response))
155/// }
156/// ```
157///
158/// When `response` serialization succeeds, the server responds with a status
159/// code of 201 Created (overwriting `Json`s default status code of 200 OK),
160/// and the expected JSON payload.
161///
162/// When `response` serialization fails hoewever, `impl IntoResponse for Json`
163/// return a response with status code 500 Internal Server Error, and
164/// `IntoResponseFailed` as a response extension, and the 201 Created override
165/// is ignored.
166///
167/// This is a behavior introduced with axum 0.9.\
168/// To force a status code override even when an inner [`IntoResponseParts`] /
169/// [`IntoResponse`] failed, use [`ForceStatusCode`].
170#[derive(Copy, Clone, Debug)]
171pub struct IntoResponseFailed;
172
173impl IntoResponseParts for IntoResponseFailed {
174    type Error = Infallible;
175
176    fn into_response_parts(self, mut res: ResponseParts) -> Result<ResponseParts, Self::Error> {
177        res.extensions_mut().insert(self);
178        Ok(res)
179    }
180}
181
182/// Not sure it makes sense to return `IntoResponseFailed` as the whole response. You should
183/// probably at least combine it with a status code.
184///
185/// ```compile_fail
186/// fn foo()
187/// where
188///     axum_core::response::IntoResponseFailed: axum_core::response::IntoResponse,
189/// {}
190/// ```
191#[allow(dead_code)]
192fn into_response_failed_doesnt_impl_into_response() {}
193
194/// Set the status code regardless of whether [`IntoResponseFailed`] is used or not.
195///
196/// See the docs for [`IntoResponseFailed`] for more details.
197#[derive(Debug, Copy, Clone, Default)]
198pub struct ForceStatusCode(pub StatusCode);
199
200impl IntoResponse for ForceStatusCode {
201    fn into_response(self) -> Response {
202        let mut res = ().into_response();
203        *res.status_mut() = self.0;
204        res
205    }
206}
207
208impl<R> IntoResponse for (ForceStatusCode, R)
209where
210    R: IntoResponse,
211{
212    fn into_response(self) -> Response {
213        let (ForceStatusCode(status), res) = self;
214        let mut res = res.into_response();
215        *res.status_mut() = status;
216        res
217    }
218}