Skip to content
Myr

main.rs

This file

Path

examples/error-handling/src/main.rs

254 lines · 8.3 KiB · Rust

Last changed by

Error handling example not displaying the correct behavior (#3788)Billard Philippebefore adoptione1f5f5e

History of this file

Take it

1//! Example showing how to convert errors into responses.2//!3//! Run with4//!5//! ```not_rust6//! cargo run -p example-error-handling7//! ```8//!9//! For successful requests the log output will be10//!11//! ```ignore12//! DEBUG request{method=POST uri=/users matched_path="/users"}: tower_http::trace::on_request: started processing request13//! DEBUG request{method=POST uri=/users matched_path="/users"}: tower_http::trace::on_response: finished processing request latency=0 ms status=20014//! ```15//!16//! For failed requests the log output will be17//!18//! ```ignore19//! DEBUG request{method=POST uri=/users matched_path="/users"}: tower_http::trace::on_request: started processing request20//! ERROR request{method=POST uri=/users matched_path="/users"}: example_error_handling: error from time_library err=failed to get time21//! DEBUG request{method=POST uri=/users matched_path="/users"}: tower_http::trace::on_response: finished processing request latency=0 ms status=50022//! ```2324use std::{25    collections::HashMap,26    sync::{27        atomic::{AtomicU64, Ordering},28        Arc, Mutex,29    },30};3132use axum::{33    extract::{rejection::JsonRejection, FromRequest, MatchedPath, Request, State},34    http::StatusCode,35    middleware::{from_fn, Next},36    response::{IntoResponse, Response},37    routing::post,38    Router,39};40use serde::{Deserialize, Serialize};41use time_library::Timestamp;42use tower_http::trace::TraceLayer;43use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};4445#[tokio::main]46async fn main() {47    tracing_subscriber::registry()48        .with(49            tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| {50                format!("{}=debug,tower_http=debug", env!("CARGO_CRATE_NAME")).into()51            }),52        )53        .with(tracing_subscriber::fmt::layer())54        .init();5556    let state = AppState::default();5758    let app = Router::new()59        // A dummy route that accepts some JSON but sometimes fails60        .route("/users", post(users_create))61        // Layers wraps from the inside out, each new .layer() call becomes the outer one.62        // Putting TraceLayer outermost means its `request` span is entered before63        // log_app_errors runs, so our tracing::error! events inherit that span and get64        // prefixed with `request{method=… uri=… matched_path=…}:`.65        .layer(from_fn(log_app_errors)) // <- Inner layer66        .layer(67            TraceLayer::new_for_http()68                // Create our own span for the request and include the matched path. The matched69                // path is useful for figuring out which handler the request was routed to.70                .make_span_with(|req: &Request| {71                    let method = req.method();72                    let uri = req.uri();7374                    // axum automatically adds this extension.75                    let matched_path = req76                        .extensions()77                        .get::<MatchedPath>()78                        .map(|matched_path| matched_path.as_str());7980                    tracing::debug_span!("request", %method, %uri, matched_path)81                })82                // By default `TraceLayer` will log 5xx responses but we're doing our specific83                // logging of errors so disable that84                .on_failure(()),85        ) // <- Outer layer86        .with_state(state);8788    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")89        .await90        .unwrap();91    tracing::debug!("listening on {}", listener.local_addr().unwrap());92    let _ = axum::serve(listener, app).await;93}9495#[derive(Default, Clone)]96struct AppState {97    next_id: Arc<AtomicU64>,98    users: Arc<Mutex<HashMap<u64, User>>>,99}100101#[derive(Deserialize)]102struct UserParams {103    name: String,104}105106#[derive(Serialize, Clone)]107struct User {108    id: u64,109    name: String,110    created_at: Timestamp,111}112113async fn users_create(114    State(state): State<AppState>,115    // Make sure to use our own JSON extractor so we get input errors formatted in a way that116    // matches our application117    AppJson(params): AppJson<UserParams>,118) -> Result<AppJson<User>, AppError> {119    let id = state.next_id.fetch_add(1, Ordering::SeqCst);120121    // We have implemented `From<time_library::Error> for AppError` which allows us to use `?` to122    // automatically convert the error123    let created_at = Timestamp::now()?;124125    let user = User {126        id,127        name: params.name,128        created_at,129    };130131    state.users.lock().unwrap().insert(id, user.clone());132133    Ok(AppJson(user))134}135136// Create our own JSON extractor by wrapping `axum::Json`. This makes it easy to override the137// rejection and provide our own which formats errors to match our application.138//139// `axum::Json` responds with plain text if the input is invalid.140#[derive(FromRequest)]141#[from_request(via(axum::Json), rejection(AppError))]142struct AppJson<T>(T);143144impl<T> IntoResponse for AppJson<T>145where146    axum::Json<T>: IntoResponse,147{148    fn into_response(self) -> Response {149        axum::Json(self.0).into_response()150    }151}152153// The kinds of errors we can hit in our application.154#[derive(Debug)]155enum AppError {156    // The request body contained invalid JSON157    JsonRejection(JsonRejection),158    // Some error from a third party library we're using159    TimeError(time_library::Error),160}161162// Tell axum how `AppError` should be converted into a response.163impl IntoResponse for AppError {164    fn into_response(self) -> Response {165        // How we want errors responses to be serialized166        #[derive(Serialize)]167        struct ErrorResponse {168            message: String,169        }170171        let (status, message, err) = match &self {172            AppError::JsonRejection(rejection) => {173                // This error is caused by bad user input so don't log it174                (rejection.status(), rejection.body_text(), None)175            }176            AppError::TimeError(_err) => {177                // While we could simply log the error here we would introduce178                // a side-effect to our conversion, instead add the AppError to179                // the Response as an Extension180                // Don't expose any details about the error to the client181                (182                    StatusCode::INTERNAL_SERVER_ERROR,183                    "Something went wrong".to_owned(),184                    Some(self),185                )186            }187        };188189        let mut response = (status, AppJson(ErrorResponse { message })).into_response();190        if let Some(err) = err {191            // Insert our error into the response, our logging middleware will use this.192            // By wrapping the error in an Arc we can use it as an Extension regardless of any inner types not deriving Clone.193            response.extensions_mut().insert(Arc::new(err));194        }195        response196    }197}198199impl From<JsonRejection> for AppError {200    fn from(rejection: JsonRejection) -> Self {201        Self::JsonRejection(rejection)202    }203}204205impl From<time_library::Error> for AppError {206    fn from(error: time_library::Error) -> Self {207        Self::TimeError(error)208    }209}210211// Our middleware is responsible for logging error details internally212async fn log_app_errors(request: Request, next: Next) -> Response {213    let response = next.run(request).await;214    // If the response contains an AppError Extension, log it.215    if let Some(err) = response.extensions().get::<Arc<AppError>>() {216        tracing::error!(?err, "an unexpected error occurred inside a handler");217    }218    response219}220221// Imagine this is some third party library that we're using. It sometimes returns errors which we222// want to log.223mod time_library {224    use std::sync::atomic::{AtomicU64, Ordering};225226    use serde::Serialize;227228    #[derive(Serialize, Clone)]229    pub struct Timestamp(u64);230231    impl Timestamp {232        pub fn now() -> Result<Self, Error> {233            static COUNTER: AtomicU64 = AtomicU64::new(0);234235            // Fail on every third call just to simulate errors236            if COUNTER.fetch_add(1, Ordering::SeqCst).is_multiple_of(3) {237                Err(Error::FailedToGetTime)238            } else {239                Ok(Self(1337))240            }241        }242    }243244    #[derive(Debug, Clone)]245    pub enum Error {246        FailedToGetTime,247    }248249    impl std::fmt::Display for Error {250        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {251            write!(f, "failed to get time")252        }253    }254}