I am trying to build on the example server in axum by adding a handle_error
builder along with State
: axum::error_handling - Rust
pub async fn init() -> Result<(), tokio::io::Error> {
let state = ServerState { client: 1 };
let app = Router::new()
.route(
"/",
get(stuff)
)
.with_state(state)
.handle_error(handle_error);
// run our app with hyper, listening globally on port 3000
let listener = tokio::net::TcpListener::bind("0.0.0.0:2772").await?;
axum::serve(listener, app.into()).await
}
async fn handle_error(err: BoxError) -> Result<(StatusCode, String), Infallible> {
Ok::<_, Infallible>((
StatusCode::INTERNAL_SERVER_ERROR,
format!("Unhandled internal error: {}", err),
))
}
But for some reason this handle_error
builder isn't documented for when you have state as well.
How can I make sense of this compilation error to get errors handled with state?:
error[E0283]: type annotations needed
--> src/route.rs:22:10
|
22 | .handle_error(handle_error);
| ^^^^^^^^^^^^
|
= note: multiple `impl`s satisfying `Router<_>: Service<_>` found in the `axum` crate:
- impl Service<IncomingStream<'_>> for Router;
- impl<B> Service<axum::http::Request<B>> for Router
where <B as HttpBody>::Data == axum::body::Bytes, B: HttpBody, B: Send, B: 'static, <B as HttpBody>::Error: Into<Box<(dyn StdError + Send + Sync + 'static)>>;
note: required by a bound in `axum::ServiceExt::handle_error`
--> /usr/local/cargo/registry/src/index.crates.io-6f17d22bba15001f/axum-0.7.9/src/service_ext.rs:8:26
|
8 | pub trait ServiceExt<R>: Service<R> + Sized {
| ^^^^^^^^^^ required by this bound in `ServiceExt::handle_error`
...
42 | fn handle_error<F, T>(self, f: F) -> HandleError<Self, F, T> {
| ------------ required by a bound in this associated function
help: try using a fully qualified path to specify the expected types
|
16 ~ let app = <Router<S2> as axum::ServiceExt<R>>::handle_error::<_, T>(Router::new()
17 | .route(
...
20 | )
21 ~ .with_state(state), handle_error);
I need state as my routes must interact with other services tracking and caching data. I need error handler because those other services throw errors that must all be converted to axum errors.