alien-error 1.3.3

Error types for the Alien platform
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
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
#[cfg(test)]
mod tests {
    use alien_error::{AlienError, AlienErrorData, Context, GenericError, IntoAlienError, Result};
    use serde::{Deserialize, Serialize};
    use serde_json;
    use std::io;

    // Simulate "crate A" errors
    #[derive(Debug, AlienErrorData, Serialize, Deserialize, Clone)]
    pub enum CrateAError {
        #[error(
            code = "DB_CONNECTION_FAILED",
            message = "Database connection failed: {reason}",
            retryable = "true",
            internal = "false"
        )]
        DatabaseConnectionFailed { reason: String },

        #[error(
            code = "DB_QUERY_FAILED",
            message = "Query failed: {query}",
            retryable = "false",
            internal = "false"
        )]
        QueryFailed { query: String, error_code: i32 },

        #[error(
            code = "DB_INTERNAL",
            message = "Internal database error",
            retryable = "false",
            internal = "true"
        )]
        InternalError,
    }

    // Simulate "crate B" errors that might wrap crate A errors
    #[derive(Debug, AlienErrorData, Serialize, Deserialize, Clone)]
    pub enum CrateBError {
        #[error(
            code = "SERVICE_UNAVAILABLE",
            message = "Service unavailable: {service}",
            retryable = "true",
            internal = "false"
        )]
        ServiceUnavailable { service: String },

        #[error(
            code = "INVALID_REQUEST",
            message = "Invalid request: {message}",
            retryable = "false",
            internal = "false"
        )]
        InvalidRequest { message: String },

        #[error(
            code = "CONFIG_ERROR",
            message = "Configuration error",
            retryable = "false",
            internal = "true"
        )]
        ConfigError,
    }

    // Helper function to simulate a database operation that fails
    fn failing_db_operation() -> Result<String, CrateAError> {
        Err(AlienError::new(CrateAError::QueryFailed {
            query: "SELECT * FROM users".to_string(),
            error_code: 1054,
        }))
    }

    // Helper function that wraps a database error with service context
    fn service_operation() -> Result<String, CrateBError> {
        failing_db_operation().context(CrateBError::ServiceUnavailable {
            service: "user-service".to_string(),
        })
    }

    // Helper function that returns a std::io::Error
    fn io_operation() -> std::io::Result<String> {
        Err(io::Error::new(io::ErrorKind::NotFound, "file not found"))
    }

    #[test]
    fn test_basic_alien_error_creation() {
        let error = AlienError::new(CrateAError::DatabaseConnectionFailed {
            reason: "timeout".to_string(),
        });

        assert_eq!(error.code, "DB_CONNECTION_FAILED");
        assert_eq!(error.message, "Database connection failed: timeout");
        assert!(error.retryable);
        assert!(!error.internal);
        assert!(error.source.is_none());
    }

    #[test]
    fn test_context_serialization() {
        let error = AlienError::new(CrateAError::QueryFailed {
            query: "SELECT * FROM users".to_string(),
            error_code: 1054,
        });

        let context = error.context.unwrap();
        assert_eq!(context["query"], "SELECT * FROM users");
        assert_eq!(context["error_code"], 1054);
    }

    #[test]
    fn test_std_error_wrapping() {
        let result: Result<String, CrateBError> =
            io_operation()
                .into_alien_error()
                .context(CrateBError::InvalidRequest {
                    message: "Failed to read configuration file".to_string(),
                });

        let error = result.unwrap_err();
        assert_eq!(error.code, "INVALID_REQUEST");
        assert!(!error.retryable);

        // Check that the source is preserved
        assert!(error.source.is_some());
        let source = error.source.as_ref().unwrap();
        assert_eq!(source.code, "GENERIC_ERROR");
        assert!(source.message.contains("file not found"));
    }

    #[test]
    fn test_alien_error_chaining() {
        let result = service_operation();
        let error = result.unwrap_err();

        // Top level error
        assert_eq!(error.code, "SERVICE_UNAVAILABLE");
        assert!(error.retryable); // Should be true from ServiceUnavailable
        assert!(!error.internal);

        // Check the error chain
        assert!(error.source.is_some());
        let source = error.source.as_ref().unwrap();
        assert_eq!(source.code, "DB_QUERY_FAILED");
        assert!(!source.retryable); // QueryFailed is not retryable

        // Verify context is preserved in the chain
        let source_context = source.context.as_ref().unwrap();
        assert_eq!(source_context["query"], "SELECT * FROM users");
        assert_eq!(source_context["error_code"], 1054);
    }

    #[test]
    fn test_metadata_inheritance_retryable() {
        // Create a retryable error
        let retryable_error = AlienError::new(CrateAError::DatabaseConnectionFailed {
            reason: "network timeout".to_string(),
        });
        assert!(retryable_error.retryable);

        // Wrap it with a non-retryable error
        let wrapped: Result<(), CrateBError> =
            Err(retryable_error).context(CrateBError::InvalidRequest {
                message: "Request failed".to_string(),
            });

        let final_error = wrapped.unwrap_err();
        // The outer error's metadata takes precedence
        assert!(!final_error.retryable);

        // But the inner error still maintains its metadata
        assert!(final_error.source.as_ref().unwrap().retryable);
    }

    #[test]
    fn test_metadata_inheritance_internal() {
        // Create an internal error
        let internal_error = AlienError::new(CrateAError::InternalError);
        assert!(internal_error.internal);

        // Wrap it with a non-internal error
        let wrapped: Result<(), CrateBError> =
            Err(internal_error).context(CrateBError::ServiceUnavailable {
                service: "auth-service".to_string(),
            });

        let final_error = wrapped.unwrap_err();
        // The outer error is not internal
        assert!(!final_error.internal);

        // But the inner error still is
        assert!(final_error.source.as_ref().unwrap().internal);
    }

    #[test]
    fn test_json_serialization_with_chain() {
        let result = service_operation();
        let error = result.unwrap_err();

        let json = serde_json::to_value(&error).unwrap();

        // Check top-level fields
        assert_eq!(json["code"], "SERVICE_UNAVAILABLE");
        assert_eq!(json["retryable"], true);
        assert_eq!(json["internal"], false);

        // Check nested error
        assert!(json["source"].is_object());
        assert_eq!(json["source"]["code"], "DB_QUERY_FAILED");
        assert_eq!(json["source"]["context"]["query"], "SELECT * FROM users");
    }

    #[test]
    fn test_display_formatting() {
        let result = service_operation();
        let error = result.unwrap_err();

        let display = format!("{}", error);
        assert!(display.contains("SERVICE_UNAVAILABLE"));
        assert!(display.contains("Service unavailable: user-service"));
        assert!(display.contains("DB_QUERY_FAILED"));
        assert!(display.contains("Query failed: SELECT * FROM users"));
    }

    #[test]
    fn test_multiple_context_layers() {
        // Create a deep error chain
        let base_error = io::Error::new(io::ErrorKind::PermissionDenied, "access denied");

        let result: Result<(), CrateBError> = Err(base_error)
            .into_alien_error()
            .context(CrateAError::DatabaseConnectionFailed {
                reason: "permission denied on socket".to_string(),
            })
            .context(CrateBError::ServiceUnavailable {
                service: "database".to_string(),
            })
            .context(CrateBError::InvalidRequest {
                message: "Cannot process request due to database issues".to_string(),
            });

        let error = result.unwrap_err();

        // Verify the chain
        assert_eq!(error.code, "INVALID_REQUEST");

        let level2 = error.source.as_ref().unwrap();
        assert_eq!(level2.code, "SERVICE_UNAVAILABLE");

        let level3 = level2.source.as_ref().unwrap();
        assert_eq!(level3.code, "DB_CONNECTION_FAILED");

        let level4 = level3.source.as_ref().unwrap();
        assert_eq!(level4.code, "GENERIC_ERROR");
        assert!(level4.message.contains("access denied"));
    }

    #[test]
    fn test_empty_variant_context() {
        // Test that empty variants (no fields) have None context
        let error = AlienError::new(CrateAError::InternalError);
        assert!(error.context.is_none());
    }

    #[test]
    fn test_cross_crate_error_conversion() {
        // Simulate converting an error from one crate to another
        let crate_a_error = AlienError::new(CrateAError::QueryFailed {
            query: "INSERT INTO logs".to_string(),
            error_code: 1452,
        });

        // Convert to Result to use context
        let result: Result<(), CrateAError> = Err(crate_a_error);
        let wrapped = result.context(CrateBError::ServiceUnavailable {
            service: "logging-service".to_string(),
        });

        let final_error = wrapped.unwrap_err();

        // Verify both errors are preserved correctly
        assert_eq!(final_error.code, "SERVICE_UNAVAILABLE");
        assert_eq!(final_error.source.as_ref().unwrap().code, "DB_QUERY_FAILED");
    }

    #[test]
    fn test_error_source_trait_implementation() {
        use std::error::Error;

        let result = service_operation();
        let error = result.unwrap_err();

        // Test that we can walk the error chain using std::error::Error trait
        let source1 = error.source().unwrap();
        assert!(source1.to_string().contains("Query failed"));

        // AlienError's source should be None for the bottom error
        let alien_source = source1
            .downcast_ref::<AlienError<alien_error::GenericError>>()
            .unwrap();
        assert!(alien_source.source.is_none());
    }

    // Test module to simulate cross-crate scenarios
    mod external_crate {
        use super::*;

        #[derive(Debug, AlienErrorData, Serialize, Deserialize, Clone)]
        pub enum ExternalError {
            #[error(
                code = "EXTERNAL_ERROR",
                message = "External service error: {details}",
                retryable = "true",
                internal = "false"
            )]
            ServiceError { details: String },
        }

        pub fn external_operation() -> Result<String, ExternalError> {
            Err(AlienError::new(ExternalError::ServiceError {
                details: "Connection refused".to_string(),
            }))
        }
    }

    #[test]
    fn test_cross_module_error_handling() {
        use external_crate::external_operation;

        let result = external_operation().context(CrateBError::ServiceUnavailable {
            service: "external-api".to_string(),
        });

        let error = result.unwrap_err();
        assert_eq!(error.code, "SERVICE_UNAVAILABLE");
        assert_eq!(error.source.as_ref().unwrap().code, "EXTERNAL_ERROR");
    }

    // Tests for HTTP status codes
    #[derive(Debug, AlienErrorData, Serialize, Deserialize, Clone)]
    pub enum HttpStatusError {
        #[error(
            code = "NOT_FOUND",
            message = "Resource not found: {resource}",
            retryable = "false",
            internal = "false",
            http_status_code = 404
        )]
        NotFound { resource: String },

        #[error(
            code = "UNAUTHORIZED",
            message = "Unauthorized access",
            retryable = "false",
            internal = "false",
            http_status_code = 401
        )]
        Unauthorized,

        #[error(
            code = "STORE_OPERATION_FAILED",
            message = "Store operation failed: {message}",
            retryable = "true",
            internal = "true",
            http_status_code = 420
        )]
        StoreOperationFailed {
            /// Human-readable description of the store operation failure
            message: String,
        },

        #[error(
            code = "VALIDATION_ERROR",
            message = "Validation failed: {field}",
            retryable = "false",
            internal = "false",
            // Note: no http_status_code specified, should default to 500
        )]
        ValidationError { field: String },

        #[error(
            code = "WRAPPER_ERROR",
            message = "Wrapping error: {details}",
            retryable = "inherit",
            internal = "inherit",
            http_status_code = "inherit"
        )]
        WrapperError { details: String },
    }

    #[test]
    fn test_http_status_code_basic() {
        let not_found_error = AlienError::new(HttpStatusError::NotFound {
            resource: "user/123".to_string(),
        });
        assert_eq!(not_found_error.http_status_code, Some(404));

        let unauthorized_error = AlienError::new(HttpStatusError::Unauthorized);
        assert_eq!(unauthorized_error.http_status_code, Some(401));

        let custom_error = AlienError::new(HttpStatusError::StoreOperationFailed {
            message: "Connection timeout".to_string(),
        });
        assert_eq!(custom_error.http_status_code, Some(420));
    }

    #[test]
    fn test_http_status_code_default() {
        let validation_error = AlienError::new(HttpStatusError::ValidationError {
            field: "email".to_string(),
        });
        // Should default to 500 when http_status_code is not specified
        assert_eq!(validation_error.http_status_code, Some(500));
    }

    #[test]
    fn test_http_status_code_with_chaining() {
        // Create a chain: ValidationError (500) -> ServiceUnavailable (retryable=true, no status) -> NotFound (404)
        let base_error = AlienError::new(HttpStatusError::NotFound {
            resource: "database".to_string(),
        });

        let result: Result<(), CrateBError> =
            Err(base_error).context(CrateBError::ServiceUnavailable {
                service: "db-service".to_string(),
            });

        let final_result: Result<(), HttpStatusError> =
            result.context(HttpStatusError::ValidationError {
                field: "user_id".to_string(),
            });

        let error = final_result.unwrap_err();

        // The outermost error should have its own status code
        assert_eq!(error.http_status_code, Some(500)); // ValidationError defaults to 500

        // Check the chain maintains HTTP status codes
        let source1 = error.source.as_ref().unwrap();
        assert_eq!(source1.http_status_code, Some(500)); // ServiceUnavailable should default to 500

        let source2 = source1.source.as_ref().unwrap();
        assert_eq!(source2.http_status_code, Some(404)); // NotFound has explicit 404
    }

    #[test]
    fn test_http_status_code_serialization() {
        let error = AlienError::new(HttpStatusError::NotFound {
            resource: "user/123".to_string(),
        });

        let json = serde_json::to_value(&error).unwrap();
        assert_eq!(json["httpStatusCode"], 404);
        assert_eq!(json["code"], "NOT_FOUND");
        assert_eq!(json["message"], "Resource not found: user/123");
    }

    #[test]
    fn test_generic_error_http_status_code() {
        let generic_error = AlienError::new(GenericError {
            message: "Something went wrong".to_string(),
        });
        assert_eq!(generic_error.http_status_code, Some(500));
    }

    // Tests for Axum integration (conditionally compiled)
    #[cfg(feature = "axum")]
    mod axum_tests {
        use super::*;
        use axum::http::StatusCode;
        use axum::response::IntoResponse;

        #[test]
        fn test_axum_into_response_basic() {
            let error = AlienError::new(HttpStatusError::NotFound {
                resource: "user/123".to_string(),
            });

            let response = error.into_response();
            assert_eq!(response.status(), StatusCode::NOT_FOUND);
        }

        #[test]
        fn test_axum_into_response_custom_status() {
            let error = AlienError::new(HttpStatusError::StoreOperationFailed {
                message: "Connection timeout".to_string(),
            });

            let response = error.into_response();
            // Default behavior is external response, so internal errors get sanitized to 500
            assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
        }

        #[test]
        fn test_axum_into_response_internal_error() {
            let internal_error = AlienError::new(HttpStatusError::StoreOperationFailed {
                message: "Database credentials invalid".to_string(),
            });

            // This is marked as internal=true, so default behavior sanitizes it
            let response = internal_error.into_response();
            assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
        }

        #[test]
        fn test_axum_into_response_default_status() {
            let error = AlienError::new(HttpStatusError::ValidationError {
                field: "email".to_string(),
            });

            let response = error.into_response();
            assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR); // 500 default
        }

        #[test]
        fn test_axum_into_response_unauthorized() {
            let error = AlienError::new(HttpStatusError::Unauthorized);

            let response = error.into_response();
            assert_eq!(response.status(), StatusCode::UNAUTHORIZED); // 401
        }

        // Tests for internal response method
        #[test]
        fn test_axum_internal_response_preserves_details() {
            let internal_error = AlienError::new(HttpStatusError::StoreOperationFailed {
                message: "Sensitive database connection details".to_string(),
            });

            let response = internal_error.into_internal_response();
            // Internal response preserves the original status code
            assert_eq!(response.status(), StatusCode::from_u16(420).unwrap());
        }

        #[test]
        fn test_axum_internal_response_non_internal_error() {
            let error = AlienError::new(HttpStatusError::NotFound {
                resource: "user/123".to_string(),
            });

            let response = error.into_internal_response();
            assert_eq!(response.status(), StatusCode::NOT_FOUND);
        }

        // Tests for external response method
        #[test]
        fn test_axum_external_response_sanitizes_internal() {
            let internal_error = AlienError::new(HttpStatusError::StoreOperationFailed {
                message: "Sensitive database connection details".to_string(),
            });

            let response = internal_error.into_external_response();
            // External response sanitizes internal errors to 500
            assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
        }

        #[test]
        fn test_axum_external_response_preserves_non_internal() {
            let error = AlienError::new(HttpStatusError::NotFound {
                resource: "user/123".to_string(),
            });

            let response = error.into_external_response();
            assert_eq!(response.status(), StatusCode::NOT_FOUND);
        }

        #[tokio::test]
        async fn test_axum_response_body() {
            use axum::body::Body;
            use axum::http::Response;

            let error = AlienError::new(HttpStatusError::NotFound {
                resource: "user/123".to_string(),
            });

            let response: Response<Body> = error.into_response();
            assert_eq!(response.status(), StatusCode::NOT_FOUND);

            // Extract and verify the JSON body
            let body_bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
                .await
                .unwrap();
            let body_str = String::from_utf8(body_bytes.to_vec()).unwrap();

            // Parse the JSON response
            let json: serde_json::Value = serde_json::from_str(&body_str).unwrap();
            assert_eq!(json["code"], "NOT_FOUND");
            assert_eq!(json["message"], "Resource not found: user/123");
            assert_eq!(json["httpStatusCode"], 404);
            assert_eq!(json["retryable"], false);
            assert_eq!(json["internal"], false);
        }

        #[tokio::test]
        async fn test_axum_external_response_body_internal_error() {
            use axum::body::Body;
            use axum::http::Response;

            let error = AlienError::new(HttpStatusError::StoreOperationFailed {
                message: "Sensitive database error details".to_string(),
            });

            let response: Response<Body> = error.into_external_response();
            assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);

            // Extract and verify the JSON body - should be sanitized
            let body_bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
                .await
                .unwrap();
            let body_str = String::from_utf8(body_bytes.to_vec()).unwrap();

            // Parse the JSON response
            let json: serde_json::Value = serde_json::from_str(&body_str).unwrap();
            assert_eq!(json["code"], "GENERIC_ERROR");
            assert_eq!(json["message"], "Internal server error");
            assert_eq!(json["httpStatusCode"], 500); // Generic error defaults to 500
            assert_eq!(json["internal"], false); // Generic errors are not internal
        }

        #[tokio::test]
        async fn test_axum_internal_response_body_preserves_details() {
            use axum::body::Body;
            use axum::http::Response;

            let error = AlienError::new(HttpStatusError::StoreOperationFailed {
                message: "Sensitive database error details".to_string(),
            });

            let response: Response<Body> = error.into_internal_response();
            assert_eq!(response.status(), StatusCode::from_u16(420).unwrap());

            // Extract and verify the JSON body - should preserve all details
            let body_bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
                .await
                .unwrap();
            let body_str = String::from_utf8(body_bytes.to_vec()).unwrap();

            // Parse the JSON response
            let json: serde_json::Value = serde_json::from_str(&body_str).unwrap();
            assert_eq!(json["code"], "STORE_OPERATION_FAILED");
            assert_eq!(
                json["message"],
                "Store operation failed: Sensitive database error details"
            );
            assert_eq!(json["httpStatusCode"], 420);
            assert_eq!(json["retryable"], true);
            assert_eq!(json["internal"], true);

            // Context should contain the message field
            assert!(json["context"].is_object());
            assert_eq!(
                json["context"]["message"],
                "Sensitive database error details"
            );
        }
    }

    // Tests for inheritance functionality
    #[derive(Debug, AlienErrorData, Serialize, Deserialize, Clone)]
    pub enum InheritanceTestError {
        #[error(
            code = "INHERIT_RETRYABLE",
            message = "Error that inherits retryable: {message}",
            retryable = "inherit",
            internal = "false"
        )]
        InheritRetryable { message: String },

        #[error(
            code = "INHERIT_INTERNAL",
            message = "Error that inherits internal: {message}",
            retryable = "false",
            internal = "inherit"
        )]
        InheritInternal { message: String },

        #[error(
            code = "INHERIT_BOTH",
            message = "Error that inherits both: {message}",
            retryable = "inherit",
            internal = "inherit"
        )]
        InheritBoth { message: String },

        #[error(
            code = "EXPLICIT_VALUES",
            message = "Error with explicit values: {message}",
            retryable = "true",
            internal = "true"
        )]
        ExplicitValues { message: String },
    }

    #[test]
    fn test_inheritance_retryable_from_retryable_source() {
        // Create a retryable source error
        let source_error = AlienError::new(CrateAError::DatabaseConnectionFailed {
            reason: "network timeout".to_string(),
        });
        assert!(source_error.retryable);

        // Wrap with an error that inherits retryable
        let result: Result<(), InheritanceTestError> =
            Err(source_error).context(InheritanceTestError::InheritRetryable {
                message: "wrapping retryable error".to_string(),
            });

        let wrapped_error = result.unwrap_err();
        // Should inherit retryable=true from source
        assert!(wrapped_error.retryable);
        assert!(!wrapped_error.internal); // Should keep explicit internal=false
    }

    #[test]
    fn test_inheritance_retryable_from_non_retryable_source() {
        // Create a non-retryable source error
        let source_error = AlienError::new(CrateAError::QueryFailed {
            query: "SELECT * FROM users".to_string(),
            error_code: 1054,
        });
        assert!(!source_error.retryable);

        // Wrap with an error that inherits retryable
        let result: Result<(), InheritanceTestError> =
            Err(source_error).context(InheritanceTestError::InheritRetryable {
                message: "wrapping non-retryable error".to_string(),
            });

        let wrapped_error = result.unwrap_err();
        // Should inherit retryable=false from source
        assert!(!wrapped_error.retryable);
        assert!(!wrapped_error.internal); // Should keep explicit internal=false
    }

    #[test]
    fn test_inheritance_internal_from_internal_source() {
        // Create an internal source error
        let source_error = AlienError::new(CrateAError::InternalError);
        assert!(source_error.internal);

        // Wrap with an error that inherits internal
        let result: Result<(), InheritanceTestError> =
            Err(source_error).context(InheritanceTestError::InheritInternal {
                message: "wrapping internal error".to_string(),
            });

        let wrapped_error = result.unwrap_err();
        // Should inherit internal=true from source
        assert!(wrapped_error.internal);
        assert!(!wrapped_error.retryable); // Should keep explicit retryable=false
    }

    #[test]
    fn test_inheritance_internal_from_non_internal_source() {
        // Create a non-internal source error
        let source_error = AlienError::new(CrateAError::QueryFailed {
            query: "SELECT * FROM users".to_string(),
            error_code: 1054,
        });
        assert!(!source_error.internal);

        // Wrap with an error that inherits internal
        let result: Result<(), InheritanceTestError> =
            Err(source_error).context(InheritanceTestError::InheritInternal {
                message: "wrapping non-internal error".to_string(),
            });

        let wrapped_error = result.unwrap_err();
        // Should inherit internal=false from source
        assert!(!wrapped_error.internal);
        assert!(!wrapped_error.retryable); // Should keep explicit retryable=false
    }

    #[test]
    fn test_inheritance_both_flags() {
        // Create a source error that is retryable and internal
        let source_error = AlienError::new(CrateAError::DatabaseConnectionFailed {
            reason: "internal network timeout".to_string(),
        });
        // Manually create an internal retryable error since our test enum doesn't have one
        let mut source_error = source_error;
        source_error.internal = true; // Make it internal for testing

        // Wrap with an error that inherits both
        let result: Result<(), InheritanceTestError> =
            Err(source_error).context(InheritanceTestError::InheritBoth {
                message: "wrapping error".to_string(),
            });

        let wrapped_error = result.unwrap_err();
        // Should inherit both flags from source
        assert!(wrapped_error.retryable);
        assert!(wrapped_error.internal);
    }

    #[test]
    fn test_no_inheritance_with_explicit_values() {
        // Create a source error that is retryable and non-internal
        let source_error = AlienError::new(CrateAError::DatabaseConnectionFailed {
            reason: "network timeout".to_string(),
        });
        assert!(source_error.retryable);
        assert!(!source_error.internal);

        // Wrap with an error that has explicit values (should not inherit)
        let result: Result<(), InheritanceTestError> =
            Err(source_error).context(InheritanceTestError::ExplicitValues {
                message: "explicit error".to_string(),
            });

        let wrapped_error = result.unwrap_err();
        // Should use explicit values, not inherit from source
        assert!(wrapped_error.retryable); // explicit true
        assert!(wrapped_error.internal); // explicit true
    }

    #[test]
    fn test_inheritance_methods_return_correct_values() {
        // Test that the generated inheritance methods return the right values
        let inherit_retryable = InheritanceTestError::InheritRetryable {
            message: "test".to_string(),
        };
        let inherit_internal = InheritanceTestError::InheritInternal {
            message: "test".to_string(),
        };
        let inherit_both = InheritanceTestError::InheritBoth {
            message: "test".to_string(),
        };
        let explicit = InheritanceTestError::ExplicitValues {
            message: "test".to_string(),
        };

        // Check retryable_inherit method
        assert_eq!(inherit_retryable.retryable_inherit(), None); // Should inherit
        assert_eq!(inherit_internal.retryable_inherit(), Some(false)); // Explicit false
        assert_eq!(inherit_both.retryable_inherit(), None); // Should inherit
        assert_eq!(explicit.retryable_inherit(), Some(true)); // Explicit true

        // Check internal_inherit method
        assert_eq!(inherit_retryable.internal_inherit(), Some(false)); // Explicit false
        assert_eq!(inherit_internal.internal_inherit(), None); // Should inherit
        assert_eq!(inherit_both.internal_inherit(), None); // Should inherit
        assert_eq!(explicit.internal_inherit(), Some(true)); // Explicit true
    }

    #[test]
    fn test_inheritance_with_std_error_source() {
        // Test inheritance when the source is a converted std error
        let io_error = io::Error::new(io::ErrorKind::NotFound, "file not found");

        let result: Result<(), InheritanceTestError> =
            Err(io_error)
                .into_alien_error()
                .context(InheritanceTestError::InheritBoth {
                    message: "wrapping std error".to_string(),
                });

        let wrapped_error = result.unwrap_err();
        // Should inherit from GenericError (retryable=false, internal=false)
        assert!(!wrapped_error.retryable);
        assert!(!wrapped_error.internal);
    }

    #[test]
    fn test_inheritance_chain_preservation() {
        // Create a chain with inheritance and verify the source chain is preserved
        let base_error = AlienError::new(CrateAError::QueryFailed {
            query: "SELECT * FROM logs".to_string(),
            error_code: 1234,
        });

        let result: Result<(), InheritanceTestError> =
            Err(base_error).context(InheritanceTestError::InheritRetryable {
                message: "database query wrapper".to_string(),
            });

        let wrapped_error = result.unwrap_err();

        // Check inheritance worked
        assert!(!wrapped_error.retryable); // Should inherit false from QueryFailed
        assert!(!wrapped_error.internal); // Explicit false

        // Check source chain is preserved
        assert!(wrapped_error.source.is_some());
        let source = wrapped_error.source.as_ref().unwrap();
        assert_eq!(source.code, "DB_QUERY_FAILED");
        assert!(source.context.is_some());
        assert_eq!(
            source.context.as_ref().unwrap()["query"],
            "SELECT * FROM logs"
        );
        assert_eq!(source.context.as_ref().unwrap()["error_code"], 1234);
    }

    // ===== Additional HTTP Status Code Tests =====

    #[test]
    fn test_http_status_code_404_with_resource() {
        let error_data = HttpStatusError::NotFound {
            resource: "user/456".to_string(),
        };
        assert_eq!(error_data.http_status_code(), 404);
        assert_eq!(error_data.http_status_code_inherit(), Some(404));

        let error = AlienError::new(error_data);
        assert_eq!(error.http_status_code, Some(404));
        assert_eq!(error.code, "NOT_FOUND");
    }

    #[test]
    fn test_http_status_code_401_unauthorized() {
        let error_data = HttpStatusError::Unauthorized;
        assert_eq!(error_data.http_status_code(), 401);
        assert_eq!(error_data.http_status_code_inherit(), Some(401));

        let error = AlienError::new(error_data);
        assert_eq!(error.http_status_code, Some(401));
        assert_eq!(error.code, "UNAUTHORIZED");
    }

    #[test]
    fn test_http_status_code_420_custom() {
        let error_data = HttpStatusError::StoreOperationFailed {
            message: "Store write failed".to_string(),
        };
        assert_eq!(error_data.http_status_code(), 420);
        assert_eq!(error_data.http_status_code_inherit(), Some(420));

        let error = AlienError::new(error_data);
        assert_eq!(error.http_status_code, Some(420));
        assert_eq!(error.code, "STORE_OPERATION_FAILED");
    }

    #[test]
    fn test_http_status_code_validation_defaults_to_500() {
        let error_data = HttpStatusError::ValidationError {
            field: "email".to_string(),
        };
        // Should default to 500 when not specified
        assert_eq!(error_data.http_status_code(), 500);
        assert_eq!(error_data.http_status_code_inherit(), Some(500));

        let error = AlienError::new(error_data);
        assert_eq!(error.http_status_code, Some(500));
        assert_eq!(error.code, "VALIDATION_ERROR");
    }

    #[test]
    fn test_http_status_code_chaining_preserves_codes() {
        // Create a 404 error
        let not_found = AlienError::new(HttpStatusError::NotFound {
            resource: "item/123".to_string(),
        });
        assert_eq!(not_found.http_status_code, Some(404));

        // Wrap it with an unauthorized error (401)
        let result: Result<(), HttpStatusError> =
            Err(not_found).context(HttpStatusError::Unauthorized);

        let wrapped = result.unwrap_err();
        // Should use the explicit 401 from Unauthorized
        assert_eq!(wrapped.http_status_code, Some(401));

        // But the source should still have 404
        assert_eq!(wrapped.source.as_ref().unwrap().http_status_code, Some(404));
    }

    #[test]
    fn test_http_status_code_json_serialization() {
        let error = AlienError::new(HttpStatusError::NotFound {
            resource: "order/999".to_string(),
        });
        let json = serde_json::to_value(&error).unwrap();

        assert_eq!(json["code"], "NOT_FOUND");
        assert_eq!(json["httpStatusCode"], 404);
        assert_eq!(json["message"], "Resource not found: order/999");
    }

    #[test]
    fn test_http_status_code_from_std_error_defaults_500() {
        // std errors converted to AlienError should get 500
        let io_error = io::Error::new(io::ErrorKind::NotFound, "file not found");
        let alien_error = AlienError::from_std(&io_error);

        assert_eq!(alien_error.http_status_code, Some(500));
        assert_eq!(alien_error.code, "GENERIC_ERROR");
    }

    #[test]
    fn test_generic_error_defaults_to_500() {
        let generic = GenericError {
            message: "Something went wrong".to_string(),
        };

        assert_eq!(generic.http_status_code(), 500);

        let error = AlienError::new(generic);
        assert_eq!(error.http_status_code, Some(500));
        assert_eq!(error.code, "GENERIC_ERROR");
    }

    #[test]
    fn test_http_status_code_metadata_vs_alienerror() {
        // Verify that the metadata methods return the same values as AlienError fields
        let not_found = HttpStatusError::NotFound {
            resource: "test".to_string(),
        };
        let unauthorized = HttpStatusError::Unauthorized;
        let validation = HttpStatusError::ValidationError {
            field: "name".to_string(),
        };

        // Check that AlienError::new() correctly uses the metadata
        let error1 = AlienError::new(not_found.clone());
        assert_eq!(error1.http_status_code, Some(not_found.http_status_code()));

        let error2 = AlienError::new(unauthorized.clone());
        assert_eq!(
            error2.http_status_code,
            Some(unauthorized.http_status_code())
        );

        let error3 = AlienError::new(validation.clone());
        assert_eq!(error3.http_status_code, Some(validation.http_status_code()));
    }

    // ===== HTTP Status Code Inheritance Tests =====

    #[test]
    fn test_http_status_code_inherit_metadata() {
        // Test that the WrapperError has the correct inheritance metadata
        let wrapper = HttpStatusError::WrapperError {
            details: "test".to_string(),
        };

        // Should return 500 as default for the actual status code
        assert_eq!(wrapper.http_status_code(), 500);

        // But http_status_code_inherit() should return None, indicating inheritance
        assert_eq!(wrapper.http_status_code_inherit(), None);
    }

    #[test]
    fn test_http_status_code_inherit_from_404() {
        // Create a 404 error
        let not_found = AlienError::new(HttpStatusError::NotFound {
            resource: "user/123".to_string(),
        });
        assert_eq!(not_found.http_status_code, Some(404));

        // Wrap it with an error that inherits http_status_code
        let result: Result<(), HttpStatusError> =
            Err(not_found).context(HttpStatusError::WrapperError {
                details: "wrapping not found".to_string(),
            });

        let wrapped = result.unwrap_err();

        // Should inherit the 404 from the source
        assert_eq!(wrapped.http_status_code, Some(404));
        assert_eq!(wrapped.code, "WRAPPER_ERROR");

        // Source should still have 404
        assert_eq!(wrapped.source.as_ref().unwrap().http_status_code, Some(404));
        assert_eq!(wrapped.source.as_ref().unwrap().code, "NOT_FOUND");
    }

    #[test]
    fn test_http_status_code_inherit_from_401() {
        // Create a 401 error
        let unauthorized = AlienError::new(HttpStatusError::Unauthorized);
        assert_eq!(unauthorized.http_status_code, Some(401));

        // Wrap it with an error that inherits http_status_code
        let result: Result<(), HttpStatusError> =
            Err(unauthorized).context(HttpStatusError::WrapperError {
                details: "auth failed".to_string(),
            });

        let wrapped = result.unwrap_err();

        // Should inherit the 401 from the source
        assert_eq!(wrapped.http_status_code, Some(401));
    }

    #[test]
    fn test_http_status_code_inherit_from_custom_420() {
        // Create a custom 420 error
        let store_error = AlienError::new(HttpStatusError::StoreOperationFailed {
            message: "store write failed".to_string(),
        });
        assert_eq!(store_error.http_status_code, Some(420));

        // Wrap it with an error that inherits http_status_code
        let result: Result<(), HttpStatusError> =
            Err(store_error).context(HttpStatusError::WrapperError {
                details: "operation failed".to_string(),
            });

        let wrapped = result.unwrap_err();

        // Should inherit the 420 from the source
        assert_eq!(wrapped.http_status_code, Some(420));
    }

    #[test]
    fn test_http_status_code_inherit_from_default_500() {
        // Create a 500 error (ValidationError has no http_status_code, defaults to 500)
        let validation_error = AlienError::new(HttpStatusError::ValidationError {
            field: "email".to_string(),
        });
        assert_eq!(validation_error.http_status_code, Some(500));

        // Wrap it with an error that inherits http_status_code
        let result: Result<(), HttpStatusError> =
            Err(validation_error).context(HttpStatusError::WrapperError {
                details: "validation wrapper".to_string(),
            });

        let wrapped = result.unwrap_err();

        // Should inherit the 500 from the source
        assert_eq!(wrapped.http_status_code, Some(500));
    }

    #[test]
    fn test_http_status_code_inherit_from_generic_error() {
        // Create a GenericError (from std error conversion)
        let io_error = io::Error::new(io::ErrorKind::NotFound, "file not found");
        let generic_error = AlienError::from_std(&io_error);
        assert_eq!(generic_error.http_status_code, Some(500));

        // Wrap it with an error that inherits http_status_code
        let result: Result<(), HttpStatusError> =
            Err(generic_error).context(HttpStatusError::WrapperError {
                details: "io wrapper".to_string(),
            });

        let wrapped = result.unwrap_err();

        // Should inherit the 500 from GenericError
        assert_eq!(wrapped.http_status_code, Some(500));
    }

    #[test]
    fn test_http_status_code_inherit_chain() {
        // Create a deep chain with multiple inheritance layers
        let not_found = AlienError::new(HttpStatusError::NotFound {
            resource: "item/456".to_string(),
        });
        assert_eq!(not_found.http_status_code, Some(404));

        // First wrapper that inherits
        let result1: Result<(), HttpStatusError> =
            Err(not_found).context(HttpStatusError::WrapperError {
                details: "first wrapper".to_string(),
            });
        let wrapped1 = result1.unwrap_err();
        assert_eq!(wrapped1.http_status_code, Some(404)); // Inherited 404

        // Second wrapper that also inherits
        let result2: Result<(), HttpStatusError> =
            Err(wrapped1).context(HttpStatusError::WrapperError {
                details: "second wrapper".to_string(),
            });
        let wrapped2 = result2.unwrap_err();
        assert_eq!(wrapped2.http_status_code, Some(404)); // Still inherited 404

        // Verify the chain
        assert_eq!(wrapped2.code, "WRAPPER_ERROR");
        assert_eq!(wrapped2.source.as_ref().unwrap().code, "WRAPPER_ERROR");
        assert_eq!(
            wrapped2
                .source
                .as_ref()
                .unwrap()
                .source
                .as_ref()
                .unwrap()
                .code,
            "NOT_FOUND"
        );
    }

    #[test]
    fn test_http_status_code_explicit_overrides_inherit() {
        // Create a 404 error
        let not_found = AlienError::new(HttpStatusError::NotFound {
            resource: "resource/999".to_string(),
        });
        assert_eq!(not_found.http_status_code, Some(404));

        // Wrap with inherit error
        let result1: Result<(), HttpStatusError> =
            Err(not_found).context(HttpStatusError::WrapperError {
                details: "wrapper".to_string(),
            });
        let wrapped1 = result1.unwrap_err();
        assert_eq!(wrapped1.http_status_code, Some(404)); // Inherited

        // Now wrap with explicit 401 error
        let result2: Result<(), HttpStatusError> =
            Err(wrapped1).context(HttpStatusError::Unauthorized);
        let wrapped2 = result2.unwrap_err();

        // Should override with 401, not inherit 404
        assert_eq!(wrapped2.http_status_code, Some(401));
        assert_eq!(wrapped2.code, "UNAUTHORIZED");

        // But the source chain should preserve the inherited 404
        assert_eq!(
            wrapped2.source.as_ref().unwrap().http_status_code,
            Some(404)
        );
    }

    #[test]
    fn test_http_status_code_inherit_retryable_and_internal() {
        // WrapperError inherits all three: retryable, internal, and http_status_code

        // Create an internal, non-retryable 420 error
        let store_error = AlienError::new(HttpStatusError::StoreOperationFailed {
            message: "internal error".to_string(),
        });
        assert!(store_error.internal); // StoreOperationFailed is internal=true
        assert!(store_error.retryable); // StoreOperationFailed is retryable=true
        assert_eq!(store_error.http_status_code, Some(420));

        // Wrap with WrapperError that inherits everything
        let result: Result<(), HttpStatusError> =
            Err(store_error).context(HttpStatusError::WrapperError {
                details: "wrapper".to_string(),
            });
        let wrapped = result.unwrap_err();

        // Should inherit all properties from StoreOperationFailed
        assert!(wrapped.internal); // Inherited
        assert!(wrapped.retryable); // Inherited
        assert_eq!(wrapped.http_status_code, Some(420)); // Inherited
    }

    #[test]
    fn test_http_status_code_inherit_serialization() {
        // Create a 404 error and wrap it
        let not_found = AlienError::new(HttpStatusError::NotFound {
            resource: "test".to_string(),
        });

        let result: Result<(), HttpStatusError> =
            Err(not_found).context(HttpStatusError::WrapperError {
                details: "wrapper".to_string(),
            });
        let wrapped = result.unwrap_err();

        // Serialize to JSON
        let json = serde_json::to_value(&wrapped).unwrap();

        // Should have the inherited 404
        assert_eq!(json["code"], "WRAPPER_ERROR");
        assert_eq!(json["httpStatusCode"], 404);
        assert_eq!(json["message"], "Wrapping error: wrapper");

        // Source should also have 404
        assert_eq!(json["source"]["httpStatusCode"], 404);
        assert_eq!(json["source"]["code"], "NOT_FOUND");
    }
}