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 fileTake it
The walk stopped after 200 commits: lines older than dcbcf5c point at it.
axum-extra: Make typed-routing feature enable routing feature (#3514)tottotobefore adoptiondcbcf5c
lines 1–34why, one step back1//! 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,examples: refactor error logging in error-handling example (#3527)Paul Matternbefore adoption8389ab1
line 35why, one step back35 middleware::{from_fn, Next},axum-extra: Make typed-routing feature enable routing feature (#3514)tottotobefore adoptiondcbcf5c
lines 36–60why, one step back36 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))Error handling example not displaying the correct behavior (#3788)Billard Philippebefore adoptione1f5f5e
lines 61–65why, one step back61 // 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 layeraxum-extra: Make typed-routing feature enable routing feature (#3514)tottotobefore adoptiondcbcf5c
lines 66–84why, one step back66 .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(()),Error handling example not displaying the correct behavior (#3788)Billard Philippebefore adoptione1f5f5e
line 85why, one step back85 ) // <- Outer layeraxum-extra: Make typed-routing feature enable routing feature (#3514)tottotobefore adoptiondcbcf5c
lines 86–91why, one step back86 .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());Error handling example not displaying the correct behavior (#3788)Billard Philippebefore adoptione1f5f5e
line 92why, one step back92 let _ = axum::serve(listener, app).await;axum-extra: Make typed-routing feature enable routing feature (#3514)tottotobefore adoptiondcbcf5c
lines 93–153why, one step back93}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.examples: refactor error logging in error-handling example (#3527)Paul Matternbefore adoption8389ab1
line 154why, one step back154#[derive(Debug)]axum-extra: Make typed-routing feature enable routing feature (#3514)tottotobefore adoptiondcbcf5c
lines 155–170why, one step back155enum 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 }170examples: refactor error logging in error-handling example (#3527)Paul Matternbefore adoption8389ab1
line 171why, one step back171 let (status, message, err) = match &self {axum-extra: Make typed-routing feature enable routing feature (#3514)tottotobefore adoptiondcbcf5c
lines 172–173why, one step back172 AppError::JsonRejection(rejection) => {173 // This error is caused by bad user input so don't log itexamples: refactor error logging in error-handling example (#3527)Paul Matternbefore adoption8389ab1
line 174why, one step back174 (rejection.status(), rejection.body_text(), None)axum-extra: Make typed-routing feature enable routing feature (#3514)tottotobefore adoptiondcbcf5c
line 175why, one step back175 }examples: refactor error logging in error-handling example (#3527)Paul Matternbefore adoption8389ab1
lines 176–179why, one step back176 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 Extensionaxum-extra: Make typed-routing feature enable routing feature (#3514)tottotobefore adoptiondcbcf5c
lines 180–183why, one step back180 // Don't expose any details about the error to the client181 (182 StatusCode::INTERNAL_SERVER_ERROR,183 "Something went wrong".to_owned(),examples: refactor error logging in error-handling example (#3527)Paul Matternbefore adoption8389ab1
line 184why, one step back184 Some(self),axum-extra: Make typed-routing feature enable routing feature (#3514)tottotobefore adoptiondcbcf5c
lines 185–188why, one step back185 )186 }187 };188examples: refactor error logging in error-handling example (#3527)Paul Matternbefore adoption8389ab1
lines 189–191why, one step back189 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.Fix misplaced comment in error handling example (#3529)Paul Matternbefore adoption37a08a1
line 192why, one step back192 // By wrapping the error in an Arc we can use it as an Extension regardless of any inner types not deriving Clone.examples: refactor error logging in error-handling example (#3527)Paul Matternbefore adoption8389ab1
lines 193–195why, one step back193 response.extensions_mut().insert(Arc::new(err));194 }195 responseaxum-extra: Make typed-routing feature enable routing feature (#3514)tottotobefore adoptiondcbcf5c
lines 196–210why, one step back196 }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}210examples: refactor error logging in error-handling example (#3527)Paul Matternbefore adoption8389ab1
lines 211–220why, one step back211// 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}220axum-extra: Make typed-routing feature enable routing feature (#3514)tottotobefore adoptiondcbcf5c
lines 221–243why, one step back221// 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 }243examples: refactor error logging in error-handling example (#3527)Paul Matternbefore adoption8389ab1
line 244why, one step back244 #[derive(Debug, Clone)]axum-extra: Make typed-routing feature enable routing feature (#3514)tottotobefore adoptiondcbcf5c
lines 245–254why, one step back245 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}