mirror of
https://github.com/tokio-rs/axum.git
synced 2024-12-29 15:49:16 +01:00
8013165908
Previously, on `main`, this wouldn't compile: ```rust let app = route("/", get(handler)) .layer( ServiceBuilder::new() .timeout(Duration::from_secs(10)) .into_inner(), ) .handle_error(...) .route(...); // <-- doesn't work ``` That is because `handle_error` would be `axum::service::ServiceExt::handle_error` which returns `HandleError<_, _, _, HandleErrorFromService>` which does _not_ implement `RoutingDsl`. So you couldn't call `route`. This was caused by https://github.com/tokio-rs/axum/pull/120. Basically `handle_error` when called on a `RoutingDsl`, the resulting service should also implement `RoutingDsl`, but if called on another random service it should _not_ implement `RoutingDsl`. I don't think thats possible by having `handle_error` on `ServiceExt` which is implemented for any service, since all axum routers are also services by design. This resolves the issue by removing `ServiceExt` and moving its methods to `RoutingDsl`. Then we have more tight control over what has a `handle_error` method. `service::OnMethod` now also has a `handle_error` so you can still handle errors from random services, by doing `service::any(svc).handle_error(...)`.
37 lines
1 KiB
Rust
37 lines
1 KiB
Rust
//! Run with
|
|
//!
|
|
//! ```not_rust
|
|
//! cargo run --example static_file_server
|
|
//! ```
|
|
|
|
use axum::{prelude::*, routing::nest};
|
|
use http::StatusCode;
|
|
use std::net::SocketAddr;
|
|
use tower_http::{services::ServeDir, trace::TraceLayer};
|
|
|
|
#[tokio::main]
|
|
async fn main() {
|
|
// Set the RUST_LOG, if it hasn't been explicitly defined
|
|
if std::env::var("RUST_LOG").is_err() {
|
|
std::env::set_var("RUST_LOG", "static_file_server=debug,tower_http=debug")
|
|
}
|
|
tracing_subscriber::fmt::init();
|
|
|
|
let app = nest(
|
|
"/static",
|
|
axum::service::get(ServeDir::new(".")).handle_error(|error: std::io::Error| {
|
|
Ok::<_, std::convert::Infallible>((
|
|
StatusCode::INTERNAL_SERVER_ERROR,
|
|
format!("Unhandled internal error: {}", error),
|
|
))
|
|
}),
|
|
)
|
|
.layer(TraceLayer::new_for_http());
|
|
|
|
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
|
|
tracing::debug!("listening on {}", addr);
|
|
axum::Server::bind(&addr)
|
|
.serve(app.into_make_service())
|
|
.await
|
|
.unwrap();
|
|
}
|