Trait axum::service::ServiceExt[][src]

pub trait ServiceExt<ReqBody, ResBody>: Service<Request<ReqBody>, Response = Response<ResBody>> {
    fn handle_error<F, Res, E>(self, f: F) -> HandleError<Self, F, ReqBody>
    where
        Self: Sized,
        F: FnOnce(Self::Error) -> Result<Res, E>,
        Res: IntoResponse,
        ResBody: Body<Data = Bytes> + Send + Sync + 'static,
        ResBody::Error: Into<BoxError> + Send + Sync + 'static
, { ... }
fn check_infallible(self) -> Self
    where
        Self: Service<Request<ReqBody>, Response = Response<ResBody>, Error = Infallible> + Sized
, { ... } }
Expand description

Extension trait that adds additional methods to Service.

Provided methods

Handle errors from a service.

handle_error takes a closure that will map errors from the service into responses. The closure’s return type must be Result<T, E> where T implements IntoResponse.

Example

use axum::{service::{self, ServiceExt}, prelude::*};
use http::{Response, StatusCode};
use tower::{service_fn, BoxError};
use std::convert::Infallible;

// A service that might fail with `std::io::Error`
let service = service_fn(|_: Request<Body>| async {
    let res = Response::new(Body::empty());
    Ok::<_, std::io::Error>(res)
});

let app = route(
    "/",
    service.handle_error(|error: std::io::Error| {
        Ok::<_, Infallible>((
            StatusCode::INTERNAL_SERVER_ERROR,
            error.to_string(),
        ))
    }),
);

It works similarly to routing::Layered::handle_error. See that for more details.

Check that your service cannot fail.

That is, its error type is Infallible.

Implementors