Document how to implement IntoResponse for custom error type (#258)

Fixes https://github.com/tokio-rs/axum/issues/249
This commit is contained in:
David Pedersen 2021-08-24 12:42:10 +02:00 committed by GitHub
parent 536b8ca4ec
commit 3d4ef9dc32
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 52 additions and 2 deletions

View file

@ -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)

View file

@ -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::{