Skip to main content

axum_problem_derive/
lib.rs

1use darling::{ast, FromDeriveInput, FromVariant};
2use proc_macro::TokenStream;
3use quote::quote;
4use syn::{parse_macro_input, DeriveInput};
5
6/// Derive `IntoResponse` for an error enum, mapping each variant to an
7/// RFC 9457 problem details response.
8///
9/// # Attributes
10///
11/// Apply `#[problem(...)]` to each variant:
12///
13/// - `status = <u16>` — **required.** The HTTP status code for this variant.
14/// - `title = "<str>"` — Optional. Defaults to the standard title for the
15///   status code (e.g. 404 → "Not Found").
16/// - `mask` — Optional. Hides the error detail from the HTTP response and
17///   logs it instead. Use for 5xx errors where you don't want internal
18///   details leaking to clients.
19/// - `log = "<level>"` — Optional, only relevant when `mask` is set.
20///   Controls the tracing level used to log the masked error. One of
21///   `"error"` (default), `"warn"`, `"info"`, or `"debug"`.
22///
23/// # Example
24///
25/// ```rust,ignore
26/// use axum_problem::AxumProblem;
27/// use thiserror::Error;
28///
29/// #[derive(Debug, Error, AxumProblem)]
30/// pub enum ApiError {
31///     #[error("order {id} not found")]
32///     #[problem(status = 404)]
33///     NotFound { id: i64 },
34///
35///     #[error("access denied")]
36///     #[problem(status = 401)]
37///     Unauthorized,
38///
39///     #[error("db error: {0}")]
40///     #[problem(status = 500, mask)]          // logs at error level (default)
41///     Database(String),
42///
43///     #[error("rate limited: {0}")]
44///     #[problem(status = 429, mask, log = "warn")]  // logs at warn level
45///     RateLimited(String),
46/// }
47/// ```
48#[proc_macro_derive(AxumProblem, attributes(problem))]
49pub fn derive_axum_problem(input: TokenStream) -> TokenStream {
50    let input = parse_macro_input!(input as DeriveInput);
51
52    match ProblemInput::from_derive_input(&input) {
53        Ok(parsed) => expand_derive(parsed).into(),
54        Err(e) => e.write_errors().into(),
55    }
56}
57
58// ── Darling attribute parsing ─────────────────────────────────────────────────
59
60#[derive(Debug, FromDeriveInput)]
61#[darling(attributes(problem), supports(enum_any))]
62struct ProblemInput {
63    ident: syn::Ident,
64    generics: syn::Generics,
65    data: ast::Data<ProblemVariant, ()>,
66}
67
68#[derive(Debug, FromVariant)]
69#[darling(attributes(problem))]
70struct ProblemVariant {
71    ident: syn::Ident,
72    fields: ast::Fields<syn::Type>,
73
74    /// HTTP status code — required on every variant.
75    status: u16,
76
77    /// Optional custom title. Defaults to the standard title for the status.
78    #[darling(default)]
79    title: Option<String>,
80
81    /// If set, hides the error detail from the HTTP response and logs it.
82    /// Prevents internal details (DB errors, etc.) leaking to API clients.
83    #[darling(default)]
84    mask: bool,
85
86    /// Log level to use when `mask` is set. One of "error" (default), "warn", "info", "debug".
87    /// Ignored when `mask` is not set.
88    #[darling(default)]
89    log: Option<String>,
90}
91
92// ── Code generation ───────────────────────────────────────────────────────────
93
94fn expand_derive(input: ProblemInput) -> proc_macro2::TokenStream {
95    let ProblemInput { ident, generics, data } = input;
96    let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();
97
98    let variants = match data {
99        ast::Data::Enum(variants) => variants,
100        _ => unreachable!("darling ensures enum_any"),
101    };
102
103    let arms = variants.iter().map(|v| build_match_arm(v, &ident));
104
105    quote! {
106        #[automatically_derived]
107        impl #impl_generics ::axum::response::IntoResponse for #ident #ty_generics #where_clause {
108            fn into_response(self) -> ::axum::response::Response {
109                match self {
110                    #(#arms),*
111                }
112            }
113        }
114    }
115}
116
117fn build_match_arm(variant: &ProblemVariant, enum_ident: &syn::Ident) -> proc_macro2::TokenStream {
118    let status = variant.status;
119    let mask = variant.mask;
120
121    // Custom title or auto from status code
122    let title_expr = match &variant.title {
123        Some(t) => quote! { #t.to_owned() },
124        None => quote! { ::axum_problem::status_title(#status).to_owned() },
125    };
126
127    // Pattern to match the variant and capture fields
128    let (pattern, display_expr) = build_pattern(enum_ident, variant);
129
130    if mask {
131        // Masked: log the full error at the specified level, return generic message to client.
132        // Generate the complete tracing call as a statement so interpolation works correctly.
133        let log_stmt = match variant.log.as_deref().unwrap_or("error") {
134            "warn"  => quote! {
135                ::tracing::warn!(error = %#display_expr, status = #status,
136                    "masked error — full detail suppressed in HTTP response");
137            },
138            "info"  => quote! {
139                ::tracing::info!(error = %#display_expr, status = #status,
140                    "masked error — full detail suppressed in HTTP response");
141            },
142            "debug" => quote! {
143                ::tracing::debug!(error = %#display_expr, status = #status,
144                    "masked error — full detail suppressed in HTTP response");
145            },
146            _ => quote! {
147                ::tracing::error!(error = %#display_expr, status = #status,
148                    "masked error — full detail suppressed in HTTP response");
149            },
150        };
151        quote! {
152            #pattern => {
153                #log_stmt
154                let problem = ::axum_problem::Problem::new(#status)
155                    .title(#title_expr);
156                ::axum::response::IntoResponse::into_response(problem)
157            }
158        }
159    } else {
160        // Not masked: include the Display impl as the detail field
161        quote! {
162            #pattern => {
163                let detail = format!("{}", #display_expr);
164                let problem = ::axum_problem::Problem::new(#status)
165                    .title(#title_expr)
166                    .detail(detail);
167                ::axum::response::IntoResponse::into_response(problem)
168            }
169        }
170    }
171}
172
173fn build_pattern(
174    enum_ident: &syn::Ident,
175    variant: &ProblemVariant,
176) -> (proc_macro2::TokenStream, proc_macro2::TokenStream) {
177    let v_ident = &variant.ident;
178
179    match &variant.fields.style {
180        ast::Style::Unit => {
181            // Unit variant: MyError::Foo
182            let pattern = quote! { #enum_ident::#v_ident };
183            // For the display expression, use the enum value itself
184            let display = quote! { #enum_ident::#v_ident };
185            (pattern, display)
186        }
187        ast::Style::Tuple => {
188            // Use ref-binding on the whole enum so Display uses the thiserror
189            // template (e.g. "validation: {0}"), not just the raw inner value.
190            // `(..)` matches any number of fields, including zero.
191            let pattern = quote! { ref __self @ #enum_ident::#v_ident(..) };
192            let display = quote! { __self };
193            (pattern, display)
194        }
195        ast::Style::Struct => {
196            // Struct variant: bind by ref and use Display from the enum value
197            let pattern = quote! { ref __self @ #enum_ident::#v_ident { .. } };
198            let display = quote! { __self };
199            (pattern, display)
200        }
201    }
202}