mirror of
https://github.com/tokio-rs/axum.git
synced 2024-12-28 07:20:12 +01:00
Document how to implement IntoResponse
for custom error type (#258)
Fixes https://github.com/tokio-rs/axum/issues/249
This commit is contained in:
parent
536b8ca4ec
commit
3d4ef9dc32
2 changed files with 52 additions and 2 deletions
|
@ -8,6 +8,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|||
# Unreleased
|
||||
|
||||
- **added:** Add `Redirect::to` constructor ([#255](https://github.com/tokio-rs/axum/pull/255))
|
||||
- **added:** Document how to implement `IntoResponse` for custom error type ([#258](https://github.com/tokio-rs/axum/pull/258))
|
||||
|
||||
# 0.2.0 (23. August, 2021)
|
||||
|
||||
|
|
|
@ -32,8 +32,57 @@ pub use self::{headers::Headers, redirect::Redirect, sse::Sse};
|
|||
/// You generally shouldn't have to implement `IntoResponse` manually, as axum
|
||||
/// provides implementations for many common types.
|
||||
///
|
||||
/// A manual implementation should only be necessary if you have a custom
|
||||
/// response body type:
|
||||
/// However it might be necessary if you have a custom error type that you want
|
||||
/// to return from handlers:
|
||||
///
|
||||
/// ```rust
|
||||
/// use axum::{
|
||||
/// Router,
|
||||
/// body::Body,
|
||||
/// handler::get,
|
||||
/// http::{Response, StatusCode},
|
||||
/// response::IntoResponse,
|
||||
/// };
|
||||
///
|
||||
/// enum MyError {
|
||||
/// SomethingWentWrong,
|
||||
/// SomethingElseWentWrong,
|
||||
/// }
|
||||
///
|
||||
/// impl IntoResponse for MyError {
|
||||
/// type Body = Body;
|
||||
/// type BodyError = <Self::Body as axum::body::HttpBody>::Error;
|
||||
///
|
||||
/// fn into_response(self) -> Response<Self::Body> {
|
||||
/// let body = match self {
|
||||
/// MyError::SomethingWentWrong => {
|
||||
/// Body::from("something went wrong")
|
||||
/// },
|
||||
/// MyError::SomethingElseWentWrong => {
|
||||
/// Body::from("something else went wrong")
|
||||
/// },
|
||||
/// };
|
||||
///
|
||||
/// Response::builder()
|
||||
/// .status(StatusCode::INTERNAL_SERVER_ERROR)
|
||||
/// .body(body)
|
||||
/// .unwrap()
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // `Result<impl IntoResponse, MyError>` can now be returned from handlers
|
||||
/// let app = Router::new().route("/", get(handler));
|
||||
///
|
||||
/// async fn handler() -> Result<(), MyError> {
|
||||
/// Err(MyError::SomethingWentWrong)
|
||||
/// }
|
||||
/// # async {
|
||||
/// # hyper::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
|
||||
/// # };
|
||||
/// ```
|
||||
///
|
||||
/// Or if you have a custom body type you'll also need to implement
|
||||
/// `IntoResponse` for it:
|
||||
///
|
||||
/// ```rust
|
||||
/// use axum::{
|
||||
|
|
Loading…
Reference in a new issue