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