Extracting path using fallible services? #2446
-
SummaryFollowing the example here: https://docs.rs/axum/latest/axum/error_handling/index.html#routing-to-fallible-services I've implemented a way that I can use the Thanks! async fn get_person(
/*
Is it possible to extract the person_id (and state) here, given my implementation?
*/
) -> Result<Json<serde_json::Value>, reqwest::Error> {
let request_url = format!("https://swapi.dev/api/people/{}", "1asdf".to_owned());
let response = reqwest::get(request_url).await?;
if response.status().is_success() {
let json = response.json::<serde_json::Value>().await?;
Ok(Json(json))
} else {
Err(response.error_for_status().unwrap_err())
}
}
#[tokio::main]
async fn main() {
let client = reqwest::Client::new();
let cors = CorsLayer::new()
.allow_methods([Method::GET])
.allow_origin(Any);
let faillible_person_service = tower::service_fn(|_req| async {
let body = get_person().await?;
Ok::<_, reqwest::Error>(body.into_response())
});
let app = Router::new()
.route("/", get(get_weather))
.route_service(
"/person/:person_id",
HandleError::new(faillible_person_service, handle_reqwest_error),
)
.layer(cors)
.with_state(client);
let listener = tokio::net::TcpListener::bind("127.0.0.1:1337")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
async fn handle_reqwest_error(err: reqwest::Error) -> Response {
let status = err.status();
let status = status.unwrap_or(reqwest::StatusCode::INTERNAL_SERVER_ERROR);
let status_as_u16 = status.as_u16();
let axum_status =
StatusCode::from_u16(status_as_u16).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
let res_json = Json(serde_json::json!({
"error": {
"message": format!("Something went wrong: {}", err),
},
}));
return (axum_status, res_json).into_response();
} axum version0.7.2 |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
You can only run extractors from handler functions called by axum. get_person is just a normal rust function and isn’t called by axum. So you to pass in the right arguments like any other function yourself. I recommend you just use normal handlers without bothering with services, similarly to https://github.com/tokio-rs/axum/blob/main/examples/reqwest-response/src/main.rs |
Beta Was this translation helpful? Give feedback.
You can only run extractors from handler functions called by axum. get_person is just a normal rust function and isn’t called by axum. So you to pass in the right arguments like any other function yourself.
I recommend you just use normal handlers without bothering with services, similarly to https://github.com/tokio-rs/axum/blob/main/examples/reqwest-response/src/main.rs