Skip to content
Myr

main.rs

This file

Path

examples/customize-path-rejection/src/main.rs

143 lines · 5.1 KiB · Rust

Last changed by

Fix return types of serve futures (#3601)Jonas Plattebefore adoptionf3a95d7

History of this file

Take it

1//! Run with2//!3//! ```not_rust4//! cargo run -p example-customize-path-rejection5//! ```67use axum::{8    extract::{path::ErrorKind, rejection::PathRejection, FromRequestParts},9    http::{request::Parts, StatusCode},10    response::IntoResponse,11    routing::get,12    Router,13};14use serde::{de::DeserializeOwned, Deserialize, Serialize};15use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};1617#[tokio::main]18async fn main() {19    tracing_subscriber::registry()20        .with(21            tracing_subscriber::EnvFilter::try_from_default_env()22                .unwrap_or_else(|_| format!("{}=debug", env!("CARGO_CRATE_NAME")).into()),23        )24        .with(tracing_subscriber::fmt::layer())25        .init();2627    // build our application with a route28    let app = Router::new().route("/users/{user_id}/teams/{team_id}", get(handler));2930    // run it31    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")32        .await33        .unwrap();34    tracing::debug!("listening on {}", listener.local_addr().unwrap());35    axum::serve(listener, app).await;36}3738async fn handler(Path(params): Path<Params>) -> impl IntoResponse {39    axum::Json(params)40}4142#[derive(Debug, Deserialize, Serialize)]43struct Params {44    user_id: u32,45    team_id: u32,46}4748// We define our own `Path` extractor that customizes the error from `axum::extract::Path`49struct Path<T>(T);5051impl<S, T> FromRequestParts<S> for Path<T>52where53    // these trait bounds are copied from `impl FromRequest for axum::extract::path::Path`54    T: DeserializeOwned + Send,55    S: Send + Sync,56{57    type Rejection = (StatusCode, axum::Json<PathError>);5859    async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {60        match axum::extract::Path::<T>::from_request_parts(parts, state).await {61            Ok(value) => Ok(Self(value.0)),62            Err(rejection) => {63                let (status, body) = match rejection {64                    PathRejection::FailedToDeserializePathParams(inner) => {65                        let mut status = StatusCode::BAD_REQUEST;6667                        let kind = inner.into_kind();68                        let body = match &kind {69                            ErrorKind::WrongNumberOfParameters { .. } => PathError {70                                message: kind.to_string(),71                                location: None,72                            },7374                            ErrorKind::ParseErrorAtKey { key, .. } => PathError {75                                message: kind.to_string(),76                                location: Some(key.clone()),77                            },7879                            ErrorKind::ParseErrorAtIndex { index, .. } => PathError {80                                message: kind.to_string(),81                                location: Some(index.to_string()),82                            },8384                            ErrorKind::ParseError { .. } => PathError {85                                message: kind.to_string(),86                                location: None,87                            },8889                            ErrorKind::InvalidUtf8InPathParam { key } => PathError {90                                message: kind.to_string(),91                                location: Some(key.clone()),92                            },9394                            ErrorKind::UnsupportedType { .. } => {95                                // this error is caused by the programmer using an unsupported type96                                // (such as nested maps) so respond with `500` instead97                                status = StatusCode::INTERNAL_SERVER_ERROR;98                                PathError {99                                    message: kind.to_string(),100                                    location: None,101                                }102                            }103104                            ErrorKind::Message(msg) => PathError {105                                message: msg.clone(),106                                location: None,107                            },108109                            _ => PathError {110                                message: format!("Unhandled deserialization error: {kind}"),111                                location: None,112                            },113                        };114115                        (status, body)116                    }117                    PathRejection::MissingPathParams(error) => (118                        StatusCode::INTERNAL_SERVER_ERROR,119                        PathError {120                            message: error.to_string(),121                            location: None,122                        },123                    ),124                    _ => (125                        StatusCode::INTERNAL_SERVER_ERROR,126                        PathError {127                            message: format!("Unhandled path rejection: {rejection}"),128                            location: None,129                        },130                    ),131                };132133                Err((status, axum::Json(body)))134            }135        }136    }137}138139#[derive(Serialize)]140struct PathError {141    message: String,142    location: Option<String>,143}