axum-anyhow 0.11.3

Ergonomic error handling for Axum using anyhow
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
use crate::{hook::invoke_hook, middleware::EnrichmentContext};
use anyhow::Error;
use axum::{
    http::StatusCode,
    response::{IntoResponse, Response},
    Json,
};
use serde::Serialize;
use serde_json::Value;
use std::sync::atomic::{AtomicBool, Ordering};

/// Global flag to control whether error details should be exposed in API responses.
/// This can be set programmatically or via the `AXUM_ANYHOW_EXPOSE_ERRORS` environment variable.
static EXPOSE_ERRORS: AtomicBool = AtomicBool::new(false);

/// Sets whether error details should be exposed in API responses.
///
/// When enabled, the actual error message will be included in the `detail` field
/// of error responses. This is useful for development but should be disabled in production.
///
/// # Example
///
/// ```rust
/// use axum_anyhow::set_expose_errors;
///
/// // Enable for development
/// set_expose_errors(true);
///
/// // Disable for production
/// set_expose_errors(false);
/// ```
pub fn set_expose_errors(expose: bool) {
    EXPOSE_ERRORS.store(expose, Ordering::Relaxed);
}

/// Returns whether error details are currently being exposed.
///
/// This checks both the programmatic setting and the `AXUM_ANYHOW_EXPOSE_ERRORS`
/// environment variable. The programmatic setting takes precedence.
///
/// # Example
///
/// ```rust
/// use axum_anyhow::{set_expose_errors, is_expose_errors_enabled};
///
/// set_expose_errors(true);
/// assert!(is_expose_errors_enabled());
/// ```
pub fn is_expose_errors_enabled() -> bool {
    // Check programmatic setting first
    if EXPOSE_ERRORS.load(Ordering::Relaxed) {
        return true;
    }

    // Fall back to environment variable
    std::env::var("AXUM_ANYHOW_EXPOSE_ERRORS")
        .map(|v| v == "1" || v.eq_ignore_ascii_case("true"))
        .unwrap_or(false)
}

/// An API error that can be converted into an HTTP response.
///
/// This struct contains the HTTP status code, a title, and a detailed description
/// of the error. When converted into a response, it produces a JSON body with
/// these fields.
///
/// # JSON Response Format
///
/// ```json
/// {
///   "status": 404,
///   "title": "Not Found",
///   "detail": "The requested resource does not exist",
///   "meta": {
///     "request_id": "abc-123"
///   }
/// }
/// ```
///
/// # Example
///
/// ```rust
/// use axum::http::StatusCode;
/// use axum_anyhow::ApiError;
/// use serde_json::json;
///
/// let error = ApiError::builder()
///     .status(StatusCode::NOT_FOUND)
///     .title("Not Found")
///     .detail("User not found")
///     .meta(json!({
///         "request_id": "abc-123"
///     }))
///     .build();
/// ```
#[derive(Debug)]
pub struct ApiError {
    /// The HTTP status code for this error
    status: StatusCode,
    /// A short, human-readable summary of the error
    title: String,
    /// A detailed explanation of the error
    detail: Option<String>,
    /// Optional metadata that can be included in the error response
    meta: Option<Value>,
    /// The underlying error that caused this API error
    error: Option<Error>,
}

impl ApiError {
    /// Gets the HTTP status code
    pub fn status(&self) -> StatusCode {
        self.status
    }

    /// Gets the error title
    pub fn title(&self) -> &str {
        &self.title
    }

    /// Gets the error detail
    pub fn detail(&self) -> Option<&str> {
        self.detail.as_deref()
    }

    /// Gets the metadata, if any
    pub fn meta(&self) -> Option<&Value> {
        self.meta.as_ref()
    }

    /// Gets the underlying error, if any
    pub fn error(&self) -> Option<&Error> {
        self.error.as_ref()
    }

    /// Creates a new builder for constructing an `ApiError`.
    ///
    /// # Example
    ///
    /// ```rust
    /// use axum::http::StatusCode;
    /// use axum_anyhow::ApiError;
    /// use anyhow::anyhow;
    ///
    /// let error = ApiError::builder()
    ///     .status(StatusCode::BAD_REQUEST)
    ///     .title("Validation Error")
    ///     .detail("Email address is required")
    ///     .build();
    /// ```
    pub fn builder() -> ApiErrorBuilder {
        ApiErrorBuilder::default()
    }
    /// Converts this `ApiError` into an `anyhow::Error`.
    ///
    /// If the `ApiError` contains an underlying error, it will be returned with
    /// additional context from the title and detail. Otherwise, a new error is
    /// created from the title and detail.
    ///
    /// # Example
    ///
    /// ```rust
    /// use axum::http::StatusCode;
    /// use axum_anyhow::ApiError;
    /// use anyhow::anyhow;
    ///
    /// let api_error = ApiError::builder()
    ///     .status(StatusCode::INTERNAL_SERVER_ERROR)
    ///     .title("Database Error")
    ///     .detail("Failed to connect")
    ///     .error(anyhow!("Connection timeout"))
    ///     .build();
    ///
    /// let anyhow_error = api_error.into_error();
    /// ```
    pub fn into_error(self) -> Error {
        let msg = match self.detail {
            Some(detail) => format!("{}: {}", self.title, detail),
            None => self.title.clone(),
        };
        if let Some(error) = self.error {
            error.context(msg)
        } else {
            anyhow::anyhow!("{}", msg)
        }
    }
}

impl Default for ApiError {
    /// Creates a default `ApiError` with:
    /// - `status`: `StatusCode::INTERNAL_SERVER_ERROR`
    /// - `title`: `"Internal Error"`
    /// - `detail`: `None`
    /// - `error`: `None`
    ///
    /// # Example
    ///
    /// ```rust
    /// use axum::http::StatusCode;
    /// use axum_anyhow::ApiError;
    ///
    /// let error = ApiError::default();
    /// assert_eq!(error.status(), StatusCode::INTERNAL_SERVER_ERROR);
    /// assert_eq!(error.title(), "Internal Error");
    /// assert_eq!(error.detail(), None);
    /// assert!(error.error().is_none());
    /// ```
    fn default() -> Self {
        Self {
            status: StatusCode::INTERNAL_SERVER_ERROR,
            title: "Internal Error".to_string(),
            detail: None,
            meta: None,
            error: None,
        }
    }
}

/// Converts from `anyhow::Error` to `ApiError`.
///
/// By default, all errors are converted to 500 Internal Server Error responses.
/// Use the extension traits to specify different status codes.
///
/// Set the `AXUM_ANYHOW_EXPOSE_ERRORS` environment variable or use `set_expose_errors(true)`
/// to expose the actual error message in the detail field (useful for development).
impl<E> From<E> for ApiError
where
    E: Into<anyhow::Error>,
{
    fn from(err: E) -> Self {
        let error = err.into();
        let should_expose = is_expose_errors_enabled();

        let mut builder = ApiError::builder();
        if should_expose {
            builder = builder.detail(error.to_string());
        }
        builder.error(error).build()
    }
}

/// The JSON structure used in error responses.
#[derive(Serialize)]
struct ApiErrorResponse {
    status: u16,
    title: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    detail: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    meta: Option<Value>,
}

/// Converts from `ApiError` to an HTTP `Response`.
///
/// This implementation allows `ApiError` to be used as a return type in Axum handlers.
/// The error is serialized as JSON with the status code, title, and detail fields.
impl IntoResponse for ApiError {
    fn into_response(self) -> Response {
        let body = Json(ApiErrorResponse {
            status: self.status.as_u16(),
            title: self.title,
            detail: self.detail,
            meta: self.meta,
        });

        (self.status, body).into_response()
    }
}

/// A builder for constructing `ApiError` instances.
///
/// This builder provides a fluent interface for creating `ApiError` instances with
/// optional fields. The `status`, `title`, and `detail` fields are required and must
/// be set before calling `build()`.
///
/// # Example
///
/// ```rust
/// use axum::http::StatusCode;
/// use axum_anyhow::ApiError;
/// use anyhow::anyhow;
///
/// let error = ApiError::builder()
///     .status(StatusCode::INTERNAL_SERVER_ERROR)
///     .title("Database Error")
///     .detail("Failed to connect to the database")
///     .error(anyhow!("Connection timeout"))
///     .build();
/// ```
#[derive(Default)]
pub struct ApiErrorBuilder {
    status: Option<StatusCode>,
    title: Option<String>,
    detail: Option<String>,
    meta: Option<Value>,
    error: Option<Error>,
}

impl Clone for ApiErrorBuilder {
    fn clone(&self) -> Self {
        Self {
            status: self.status,
            title: self.title.clone(),
            detail: self.detail.clone(),
            meta: self.meta.clone(),
            // anyhow::Error doesn't implement Clone, so we skip it
            error: None,
        }
    }
}

impl ApiErrorBuilder {
    /// Sets the HTTP status code for the error.
    ///
    /// # Example
    ///
    /// ```rust
    /// use axum::http::StatusCode;
    /// use axum_anyhow::ApiError;
    ///
    /// let error = ApiError::builder()
    ///     .status(StatusCode::NOT_FOUND)
    ///     .title("Not Found")
    ///     .detail("Resource not found")
    ///     .build();
    /// ```
    pub fn status(mut self, status: StatusCode) -> Self {
        self.status = Some(status);
        self
    }

    /// Sets the title for the error.
    ///
    /// # Example
    ///
    /// ```rust
    /// use axum::http::StatusCode;
    /// use axum_anyhow::ApiError;
    ///
    /// let error = ApiError::builder()
    ///     .status(StatusCode::BAD_REQUEST)
    ///     .title("Invalid Input")
    ///     .detail("The provided email is invalid")
    ///     .build();
    /// ```
    pub fn title(mut self, title: impl Into<String>) -> Self {
        self.title = Some(title.into());
        self
    }

    /// Sets the detail message for the error.
    ///
    /// # Example
    ///
    /// ```rust
    /// use axum::http::StatusCode;
    /// use axum_anyhow::ApiError;
    ///
    /// let error = ApiError::builder()
    ///     .status(StatusCode::FORBIDDEN)
    ///     .title("Access Denied")
    ///     .detail("You do not have permission to access this resource")
    ///     .build();
    /// ```
    pub fn detail(mut self, detail: impl Into<String>) -> Self {
        self.detail = Some(detail.into());
        self
    }

    /// Sets the underlying error that caused this API error.
    ///
    /// # Example
    ///
    /// ```rust
    /// use axum::http::StatusCode;
    /// use axum_anyhow::ApiError;
    /// use anyhow::anyhow;
    ///
    /// let error = ApiError::builder()
    ///     .status(StatusCode::INTERNAL_SERVER_ERROR)
    ///     .title("Database Error")
    ///     .detail("Failed to execute query")
    ///     .error(anyhow!("Connection pool exhausted"))
    ///     .build();
    ///
    /// assert_eq!(error.status(), StatusCode::INTERNAL_SERVER_ERROR);
    /// assert_eq!(error.title(), "Database Error");
    /// assert_eq!(error.detail(), Some("Failed to execute query"));
    /// assert_eq!(error.error().unwrap().to_string(), "Connection pool exhausted");
    /// ```
    pub fn error(mut self, error: impl Into<Error>) -> Self {
        self.error = Some(error.into());
        self
    }

    /// Sets custom metadata for the error.
    ///
    /// This metadata will be included in the JSON response under the `meta` field.
    /// It can contain any JSON-serializable data, such as request IDs, trace information,
    /// or other contextual data.
    ///
    /// # Example
    ///
    /// ```rust
    /// use axum::http::StatusCode;
    /// use axum_anyhow::ApiError;
    /// use serde_json::json;
    ///
    /// let error = ApiError::builder()
    ///     .status(StatusCode::NOT_FOUND)
    ///     .title("Not Found")
    ///     .detail("User not found")
    ///     .meta(json!({"request_id": "abc-123", "timestamp": 1234567890}))
    ///     .build();
    ///
    /// assert!(error.meta().is_some());
    /// ```
    pub fn meta(mut self, meta: Value) -> Self {
        self.meta = Some(meta);
        self
    }

    /// Builds the `ApiError` instance.
    ///
    /// If `status`, `title`, or `detail` have not been set, they will default to:
    /// - `status`: `StatusCode::INTERNAL_SERVER_ERROR`
    /// - `title`: `"Internal Error"`
    /// - `detail`: `"Something went wrong"`
    ///
    /// # Example
    ///
    /// ```rust
    /// use axum::http::StatusCode;
    /// use axum_anyhow::ApiError;
    ///
    /// let error = ApiError::builder()
    ///     .status(StatusCode::BAD_REQUEST)
    ///     .title("Bad Request")
    ///     .detail("Invalid request parameters")
    ///     .build();
    ///
    /// assert_eq!(error.status(), StatusCode::BAD_REQUEST);
    /// assert_eq!(error.title(), "Bad Request");
    /// assert_eq!(error.detail(), Some("Invalid request parameters"));
    ///
    /// // Using defaults
    /// let default_error = ApiError::builder().build();
    /// assert_eq!(default_error.status(), StatusCode::INTERNAL_SERVER_ERROR);
    /// assert_eq!(default_error.title(), "Internal Error");
    /// assert_eq!(default_error.detail(), None);
    /// ```
    pub fn build(mut self) -> ApiError {
        self = EnrichmentContext::invoke(self);

        let error = ApiError {
            status: self.status.unwrap_or(StatusCode::INTERNAL_SERVER_ERROR),
            title: self.title.unwrap_or_else(|| "Internal Error".to_string()),
            detail: self.detail,
            meta: self.meta,
            error: self.error,
        };

        invoke_hook(&error);
        error
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use anyhow::anyhow;
    use http_body_util::BodyExt;
    use serde_json::Value;
    use serial_test::serial;

    #[test]
    fn test_into_api_error_from_anyhow() {
        let anyhow_err = anyhow!("Something went wrong");
        let api_err: ApiError = anyhow_err.into();

        assert_eq!(api_err.status, StatusCode::INTERNAL_SERVER_ERROR);
        assert_eq!(api_err.title, "Internal Error");
        assert_eq!(api_err.detail, None);
    }

    #[test]
    fn test_api_error_builder() {
        let error = ApiError::builder()
            .status(StatusCode::BAD_REQUEST)
            .title("Validation Error")
            .detail("Email is required")
            .build();

        assert_eq!(error.status, StatusCode::BAD_REQUEST);
        assert_eq!(error.title, "Validation Error");
        assert_eq!(error.detail, Some("Email is required".to_string()));
        assert!(error.error.is_none());
    }

    #[test]
    fn test_api_error_builder_with_error() {
        let underlying_error = anyhow!("Database connection failed");
        let error = ApiError::builder()
            .status(StatusCode::INTERNAL_SERVER_ERROR)
            .title("Database Error")
            .detail("Could not connect to the database")
            .error(underlying_error)
            .build();

        assert_eq!(error.status, StatusCode::INTERNAL_SERVER_ERROR);
        assert_eq!(error.title, "Database Error");
        assert_eq!(
            error.detail,
            Some("Could not connect to the database".to_string())
        );
        assert!(error.error.is_some());
    }

    #[test]
    fn test_api_error_builder_with_string_conversions() {
        let error = ApiError::builder()
            .status(StatusCode::NOT_FOUND)
            .title("Not Found".to_string())
            .detail("Resource not found".to_string())
            .build();

        assert_eq!(error.status, StatusCode::NOT_FOUND);
        assert_eq!(error.title, "Not Found");
        assert_eq!(error.detail, Some("Resource not found".to_string()));
    }

    #[test]
    fn test_api_error_builder_missing_status() {
        let error = ApiError::builder()
            .title("Error")
            .detail("Something went wrong")
            .build();

        assert_eq!(error.status, StatusCode::INTERNAL_SERVER_ERROR);
        assert_eq!(error.title, "Error");
        assert_eq!(error.detail, Some("Something went wrong".to_string()));
    }

    #[test]
    fn test_api_error_builder_missing_title() {
        let error = ApiError::builder()
            .status(StatusCode::BAD_REQUEST)
            .detail("Something went wrong")
            .build();

        assert_eq!(error.status, StatusCode::BAD_REQUEST);
        assert_eq!(error.title, "Internal Error");
        assert_eq!(error.detail, Some("Something went wrong".to_string()));
    }

    #[test]
    fn test_api_error_builder_missing_detail() {
        let error = ApiError::builder()
            .status(StatusCode::BAD_REQUEST)
            .title("Error")
            .build();

        assert_eq!(error.status, StatusCode::BAD_REQUEST);
        assert_eq!(error.title, "Error");
        assert_eq!(error.detail, None);
    }

    #[test]
    fn test_api_error_builder_all_defaults() {
        let error = ApiError::builder().build();

        assert_eq!(error.status, StatusCode::INTERNAL_SERVER_ERROR);
        assert_eq!(error.title, "Internal Error");
        assert_eq!(error.detail, None);
        assert!(error.error.is_none());
    }

    #[test]
    fn test_api_error_builder_fluent_interface() {
        let error = ApiError::builder()
            .status(StatusCode::CONFLICT)
            .title("Conflict")
            .detail("User already exists")
            .error(anyhow!("Duplicate email"))
            .build();

        assert_eq!(error.status, StatusCode::CONFLICT);
        assert_eq!(error.title, "Conflict");
        assert_eq!(error.detail, Some("User already exists".to_string()));
        assert!(error.error.is_some());
    }

    #[test]
    fn test_api_error_default() {
        let error = ApiError::default();

        assert_eq!(error.status, StatusCode::INTERNAL_SERVER_ERROR);
        assert_eq!(error.title, "Internal Error");
        assert_eq!(error.detail, None);
        assert!(error.error.is_none());
    }

    #[test]
    fn test_anyhow_error_coerced_to_api_error_has_defaults() {
        set_expose_errors(false);

        let anyhow_err = anyhow!("Some error occurred");
        let api_err: ApiError = anyhow_err.into();

        assert_eq!(api_err.status, StatusCode::INTERNAL_SERVER_ERROR);
        assert_eq!(api_err.title, "Internal Error");
        assert_eq!(api_err.detail, None);
        assert!(api_err.error.is_some());
    }

    #[test]
    fn test_api_error_default_matches_builder_defaults() {
        let from_default = ApiError::default();
        let from_builder = ApiError::builder().build();

        assert_eq!(from_default.status, from_builder.status);
        assert_eq!(from_default.title, from_builder.title);
        assert_eq!(from_default.detail, from_builder.detail);
        assert!(from_default.error.is_none());
        assert!(from_builder.error.is_none());
    }

    #[tokio::test]
    async fn test_into_response_status() {
        let api_err = ApiError::builder()
            .status(StatusCode::BAD_REQUEST)
            .title("Bad Request")
            .detail("Invalid data")
            .build();

        let response = api_err.into_response();
        assert_eq!(response.status(), StatusCode::BAD_REQUEST);
    }

    #[tokio::test]
    async fn test_into_response_json_structure() {
        let api_err = ApiError::builder()
            .status(StatusCode::NOT_FOUND)
            .title("Not Found")
            .detail("Resource does not exist")
            .build();

        let response = api_err.into_response();

        // Verify status
        assert_eq!(response.status(), StatusCode::NOT_FOUND);

        // Verify JSON body structure
        let body = response.into_body();
        let bytes = body.collect().await.unwrap().to_bytes();
        let json: Value = serde_json::from_slice(&bytes).unwrap();

        assert_eq!(json["status"], 404);
        assert_eq!(json["title"], "Not Found");
        assert_eq!(json["detail"], "Resource does not exist");
    }

    #[test]
    fn test_into_error_with_underlying_error() {
        let underlying = anyhow!("Connection timeout");
        let api_error = ApiError::builder()
            .status(StatusCode::INTERNAL_SERVER_ERROR)
            .title("Database Error")
            .detail("Failed to connect")
            .error(underlying)
            .build();

        let anyhow_error = api_error.into_error();
        let error_msg = format!("{:#}", anyhow_error);

        // Should contain both the context and the underlying error
        assert!(error_msg.contains("Database Error: Failed to connect"));
        assert!(error_msg.contains("Connection timeout"));
    }

    #[test]
    fn test_into_error_without_underlying_error() {
        let api_error = ApiError::builder()
            .status(StatusCode::BAD_REQUEST)
            .title("Validation Error")
            .detail("Email is required")
            .build();

        let anyhow_error = api_error.into_error();
        let error_msg = anyhow_error.to_string();

        assert_eq!(error_msg, "Validation Error: Email is required");
    }

    #[test]
    #[serial]
    fn test_expose_error_details_enabled() {
        set_expose_errors(true);

        let anyhow_err = anyhow!("Database connection failed");
        let api_err: ApiError = anyhow_err.into();

        assert_eq!(api_err.status, StatusCode::INTERNAL_SERVER_ERROR);
        assert_eq!(api_err.title, "Internal Error");
        assert_eq!(
            api_err.detail,
            Some("Database connection failed".to_string())
        );
        assert!(api_err.error.is_some());

        set_expose_errors(false);
    }

    #[test]
    #[serial]
    fn test_expose_error_details_disabled() {
        set_expose_errors(false);

        let anyhow_err = anyhow!("Database connection failed");
        let api_err: ApiError = anyhow_err.into();

        assert_eq!(api_err.status, StatusCode::INTERNAL_SERVER_ERROR);
        assert_eq!(api_err.title, "Internal Error");
        assert_eq!(api_err.detail, None);
        assert!(api_err.error.is_some());
    }

    #[test]
    #[serial]
    fn test_expose_error_details_with_true() {
        set_expose_errors(true);

        let anyhow_err = anyhow!("Connection timeout");
        let api_err: ApiError = anyhow_err.into();

        assert_eq!(api_err.detail, Some("Connection timeout".to_string()));

        set_expose_errors(false);
    }

    #[test]
    #[serial]
    fn test_expose_error_via_env_var() {
        // Ensure programmatic setting is disabled
        set_expose_errors(false);

        // Set environment variable
        unsafe {
            std::env::set_var("AXUM_ANYHOW_EXPOSE_ERRORS", "1");
        }

        let anyhow_err = anyhow!("Environment variable test");
        let api_err: ApiError = anyhow_err.into();

        // Should expose details via env var
        assert_eq!(
            api_err.detail,
            Some("Environment variable test".to_string())
        );

        // Clean up
        unsafe {
            std::env::remove_var("AXUM_ANYHOW_EXPOSE_ERRORS");
        }
    }

    #[test]
    #[serial]
    fn test_programmatic_setting_overrides_env_var() {
        // Set environment variable to disabled
        unsafe {
            std::env::set_var("AXUM_ANYHOW_EXPOSE_ERRORS", "0");
        }

        // But enable programmatically (should take precedence)
        set_expose_errors(true);

        let anyhow_err = anyhow!("Programmatic override test");
        let api_err: ApiError = anyhow_err.into();

        // Should expose details because programmatic setting takes precedence
        assert_eq!(
            api_err.detail,
            Some("Programmatic override test".to_string())
        );

        // Clean up
        set_expose_errors(false);
        unsafe {
            std::env::remove_var("AXUM_ANYHOW_EXPOSE_ERRORS");
        }
    }

    #[test]
    fn test_api_error_with_meta() {
        use serde_json::json;

        let error = ApiError::builder()
            .status(StatusCode::NOT_FOUND)
            .title("Not Found")
            .detail("User not found")
            .meta(json!({"request_id": "abc-123", "timestamp": 1234567890}))
            .build();

        assert_eq!(error.status, StatusCode::NOT_FOUND);
        assert_eq!(error.title, "Not Found");
        assert_eq!(error.detail, Some("User not found".to_string()));
        assert!(error.meta.is_some());

        let meta = error.meta.unwrap();
        assert_eq!(meta["request_id"], "abc-123");
        assert_eq!(meta["timestamp"], 1234567890);
    }

    #[test]
    fn test_api_error_without_meta() {
        let error = ApiError::builder()
            .status(StatusCode::BAD_REQUEST)
            .title("Bad Request")
            .detail("Invalid input")
            .build();

        assert!(error.meta.is_none());
    }

    #[test]
    fn test_api_error_default_has_none_meta() {
        let error = ApiError::default();
        assert!(error.meta.is_none());
    }

    #[tokio::test]
    async fn test_into_response_with_meta() {
        use serde_json::json;

        let api_err = ApiError::builder()
            .status(StatusCode::INTERNAL_SERVER_ERROR)
            .title("Server Error")
            .detail("Something went wrong")
            .meta(json!({"trace_id": "xyz-789"}))
            .build();

        let response = api_err.into_response();

        // Verify status
        assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);

        // Verify JSON body includes meta
        let body = response.into_body();
        let bytes = body.collect().await.unwrap().to_bytes();
        let json: Value = serde_json::from_slice(&bytes).unwrap();

        assert_eq!(json["status"], 500);
        assert_eq!(json["title"], "Server Error");
        assert_eq!(json["detail"], "Something went wrong");
        assert!(json["meta"].is_object());
        assert_eq!(json["meta"]["trace_id"], "xyz-789");
    }

    #[tokio::test]
    async fn test_into_response_without_meta() {
        let api_err = ApiError::builder()
            .status(StatusCode::NOT_FOUND)
            .title("Not Found")
            .detail("Resource not found")
            .build();

        let response = api_err.into_response();

        // Verify JSON body does not include meta field
        let body = response.into_body();
        let bytes = body.collect().await.unwrap().to_bytes();
        let json: Value = serde_json::from_slice(&bytes).unwrap();

        assert_eq!(json["status"], 404);
        assert_eq!(json["title"], "Not Found");
        assert_eq!(json["detail"], "Resource not found");
        // Meta should be omitted from JSON when None (due to skip_serializing_if)
        assert!(json.get("meta").is_none());
    }

    #[test]
    fn test_api_error_builder_fluent_with_meta() {
        use serde_json::json;

        let error = ApiError::builder()
            .status(StatusCode::CONFLICT)
            .title("Conflict")
            .detail("Resource already exists")
            .meta(json!({"duplicate_field": "email", "value": "test@example.com"}))
            .error(anyhow!("Unique constraint violation"))
            .build();

        assert_eq!(error.status, StatusCode::CONFLICT);
        assert_eq!(error.title, "Conflict");
        assert_eq!(error.detail, Some("Resource already exists".to_string()));
        assert!(error.error.is_some());
        assert!(error.meta.is_some());

        let meta = error.meta.unwrap();
        assert_eq!(meta["duplicate_field"], "email");
        assert_eq!(meta["value"], "test@example.com");
    }
}