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
//! [![github]](https://github.com/calizoots/luhtwin) [![crates-io]](https://crates.io/crates/luhtwin) [![docs-rs]](https://docs.rs/luhtwin)
//!
//! [github]: https://img.shields.io/badge/github-calizoots/anyhow-8da0cb?style=for-the-badge&labelColor=555555&logo=github
//! [crates-io]: https://img.shields.io/crates/v/luhtwin.svg?style=for-the-badge&color=fc8d62&logo=rust
//! [docs-rs]: https://img.shields.io/badge/docs.rs-luhtwin-66c2a5?style=for-the-badge&labelColor=555555&logo=docs.rs
//!
//! # luhtwin - Horrible Error Handling for Rust
//!
//! `luhtwin` provides a ergonomic error handling system that emphasizes
//! **context accumulation**, **structured diagnostics**, and **flexible formatting**.
//! Built around the [`AnyError`] type, it allows you to wrap any error with rich
//! metadata and progressively add context as errors bubble up through your application.
//!
//! ## Core Ideas
//!
//! - **[`AnyError`]** — The main error container that wraps any `Error` type with context chains
//! - **[`LuhTwin<T>`]** — Type alias for `Result<T, AnyError>`, the primary result type
//! - **[`ErrorContext`]** — Structured metadata including messages, file/line info, docs, and severity
//! - **[`Wrap`]** — Wrapping existing Results into LuhTwin.
//! - **[`Twin`]** — Transforming existing Results into LuhTwin.
//! - **[`Encase`]** — Encase existing LuhTwins in another layer of context.
//!
//! ## Getting Started
//!
//! Add `luhtwin` to your `Cargo.toml`:
//!
//! ```toml
//! [dependencies]
//! luhtwin = "0.1.4"
//! ```
//!
//! ## Quick Example
//!
//! ```ignore
//! use luhtwin::{LuhTwin, Twin, Wrap, Encase, at};
//! use std::fs;
//! use std::io;
//!
//! fn read_config_file(path: &str) -> LuhTwin<String> {
//! fs::read_to_string(path)
//! .wrap(|| format!("failed to read config from {}", path))
//! }
//!
//! fn parse_config(content: String) -> LuhTwin<Config> {
//! serde_json::from_str(&content)
//! .twin()
//! .encase(|| "failed to parse config as JSON")
//! }
//!
//! fn load_config() -> LuhTwin<Config> {
//! let content = read_config_file("config.json")?;
//! parse_config(content)
//! .encase(|| "config loading failed")
//! }
//!
//! fn main() -> LuhTwin<()> {
//! let config = load_config()?;
//! println!("Config loaded successfully!");
//! Ok(())
//! }
//! ```
//!
//! ## Error Output
//!
//! When an error occurs, `luhtwin` provides detailed, layered context:
//!
//! ```text
//! LUHTWIN_FULL=1 to see full errors <3
//! 1: failed to read config from config.json: No such file or directory
//! 2: failed to parse config as JSON
//! 3: config loading failed
//! source: No such file or directory (os error 2)
//! backtrace:
//! disabled backtrace
//! ```
//!
//! With `LUHTWIN_FULL=1`, you get the full context including file/line info:
//!
//! ```text
//! 1: failed to read config from config.json: No such file or directory
//! - file: "src/main.rs"
//! - line: 8
//!
//! 2: failed to parse config as JSON
//! - file: "src/main.rs"
//! - line: 14
//!
//! 3: config loading failed
//! - file: "src/main.rs"
//! - line: 19
//! ```
//!
//! ## Common Patterns
//!
//! ### Converting foreign errors with `.twin()`
//!
//! ```ignore
//! use std::fs::File;
//!
//! fn open_file() -> LuhTwin<File> {
//! File::open("data.txt").twin()
//! }
//! ```
//!
//! ### Wrapping errors with context using `.wrap()`
//!
//! ```ignore
//! fn read_user_data(id: u32) -> LuhTwin<UserData> {
//! read_from_db(id).wrap(|| format!("failed to load user {}", id))
//! }
//! ```
//!
//! ### Adding layers with `.encase()`
//!
//! ```ignore
//! fn initialize() -> LuhTwin<()> {
//! load_config()
//! .encase(|| "initialization failed")?;
//! connect_db()
//! .encase(|| "initialization failed")?;
//! Ok(())
//! }
//! ```
//!
//! ### Using the `at!` macro for rich context
//!
//! ```ignore
//! fn validate_input(input: &str) -> LuhTwin<()> {
//! if input.is_empty() {
//! return Err(at!("input validation failed")
//! .attach("input", input)
//! .attach("expected", "non-empty string")
//! .into());
//! }
//! Ok(())
//! }
//! ```
//!
//! ## Environment Variables
//!
//! - `LUHTWIN_FULL=1` - Show full error details with all attached arguments
//! - `RUST_BACKTRACE=1` - Enable backtrace capture (standard Rust behavior)
//!
use Backtrace;
use env;
use Error;
use Any;
use ;
/// Just a base trait ease of refactoring <3
pub type ErrorSource = ;
/// # ErrorArg
///
/// All arguments passed to an `luhtwin::ErrorContext` must provide these 3 things
///
/// `fn name(&self) -> &str` -> returns the name of the value
/// `fn display(&self) -> String` -> returns a string which corresponds to output in console
/// `fn as_any(&self) -> &dyn Any` -> returns an trait object Any or in other words a borrow to a
/// shared reference can be used to dereference to get original value in code if needs really be
/// # Arg
///
/// The default implementation of `luhtwin::ErrorArg` (you can write your own)
///
/// ## note
///
/// `Arg::display()` always returns the debug display of your value
/// # ErrorContext
///
/// The main context type for `luhtwin::AnyError` fairly simple
/// contains a message and a list of Arguments which all follow a trait
/// so you can roll your own. See `luhtwin::Arg` and `luhtwin::ErrorArg` trait
///
/// ## Provided Methods
///
/// ## `fn new(msg: impl Into<String>) -> ErrorContext`
///
/// Returns a new ErrorContext with provided message and empty arguments
///
/// ## `fn attach_other<E: ErrorArg + 'static>(mut self, arg: E) -> ErrorContext`
///
/// Pushes a new argument (implementing `luhtwin::ErrorArg`) to self.args and returns itself
///
/// ## `fn attach<T: Debug + Send + Sync + 'static>(mut self, name: impl Into<String>, value: T) -> ErrorContext`
///
/// Pushes a new argument with the given name with an unspecified type and returns itself
///
/// ## `fn file(mut self, file: impl Into<String>) -> Self`
///
/// Adds an argument with a predefined name "file"
///
/// ## `fn line(mut self, line: u32) -> Self`
///
/// Adds an argument with a predefined name "line"
///
/// ## `fn into_error(self) -> AnyError`
///
/// Calls into on itself useful for when you need a specified type
///
/// ## Examples
///
/// The main way to interface with an `luhtwin::ErrorContext` is with the `luhtwin::at` macro
/// here is a basic example of that but do read the at macro documentation
///
/// ```ignore
/// fn main() -> LuhTwin<()> {
/// Err(at!("oopsie happened")
/// .attach("issues", vec!["only", "possible", "issue"]).into())
/// }
/// ```
///
/// Or you could construct one manually
///
/// ```ignore
/// let ctx = ErrorContext::new("oops oh no happened")
/// .file(file!())
/// .line(line!())
/// .attach("issues", vec!["#12042", "#12079"])
/// ```
// easy convertions from string types to ErrorContext
/// # AnyError
///
/// The main error type in this library used in `luhtwin:LuhTwin` which is a
/// Result<T, AnyError>... AnyError provides a lot of flexibility with a list
/// of ErrorContext(s) also provides a Backtrace and an optional source see `luhtwin::ErrorSource`
///
/// Rarely will you interface with this type by itself rather in predefined abstractions
/// given to you see `luhtwin::Wrap`, `luhtwin::Encase`, `luhtwin::Twin` and `luhtwin::Context`
///
/// ## Provided Methods
///
/// ## `fn new<E>(err: E) -> AnyError where E: Error + Send + Sync + 'static`
///
/// Takes all the error types you could want and turn them into an AnyError with an empty context
/// will capture a backtrace if enabled through RUST_BACKTRACE=1
///
/// ## `fn with_context(mut self, ctx: ErrorContext) -> AnyError`
///
/// Appends the given context to self.contexts
///
/// ## `fn root_cause(&self) -> &(dyn Error + 'static)`
///
/// Returns the first error in self.contexts in other words the root cause
///
/// ## `fn iter_sources(&self) -> impl Iterator<Item = &(dyn Error + 'static)> + '_ `
///
/// This is just remnants from the last version kept here for ease of use don't use though
/// its just dumb lmao
///
/// ## Examples
///
/// As I said beforehand you would rarely use this by itself you would use it like this
///
/// ```ignore
/// fn this_fails() -> LuhTwin<()> {
/// Err(io::Error::new(io::ErrorKind::Other, "file missing")
/// .twin())
/// }
/// fn main() -> LuhTwin<()> {
/// this_fails().encase(|| "it failed like expected")?;
/// Ok(())
/// }
/// ```
///
/// Or wrap pre-existing errors
///
/// ```ignore
/// fn this_fails() -> Result<(), io::Error> {
/// Err(io::Error::new(io::ErrorKind::Other, "idk what happened"))
/// }
/// fn main() -> LuhTwin<()> {
/// this_fails().wrap(|| "it failed")?;
/// Ok(())
/// }
/// ```
/// # LuhTwin
///
/// A wrapper type for a Result with an AnyError it is just an alias though
/// gives you access through traits such as `luhtwin::Twin`, `luhtwin::Wrap`,
/// `luhtwin::Encase` and `luhtwin::Context` to chain different errors together
/// of different types
///
/// ## Examples
///
/// Encasing pre-existing LuhTwin Errors
///
/// ```ignore
/// fn this_fails() -> LuhTwin<()> {
/// Err(io::Error::new(io::ErrorKind::Other, "file missing")
/// .twin())
/// }
/// fn main() -> LuhTwin<()> {
/// this_fails().encase(|| "it failed like expected")?;
/// Ok(())
/// }
/// ```
///
/// Wrapping pre-existing other errors
///
/// ```ignore
/// fn this_fails() -> Result<(), io::Error> {
/// Err(io::Error::new(io::ErrorKind::Other, "idk what happened"))
/// }
/// fn main() -> LuhTwin<()> {
/// this_fails().wrap(|| "it failed")?;
/// Ok(())
/// }
/// ```
///
/// Context Chaining
///
/// ```ignore
/// let err: Result<(), io::Error> = Err(io::Error::new(io::ErrorKind::Other, "root"));
/// let result = err
/// .context("loading data")
/// .context("initializing system");
/// assert!(result.is_err());
/// let e = result.unwrap_err();
/// assert_eq!(e.to_string(), "initializing system");
/// let src1 = e.source().unwrap();
/// assert_eq!(src1.to_string(), "loading data");
/// let src2 = src1.source().unwrap();
/// assert_eq!(src2.to_string(), "root");
/// ```
pub type LuhTwin<T> = ;
/// # BigTwin
///
/// A generic alias for a Result
pub type BigTwin<T, E> = ;
/// # Twin
///
/// Converts any `Result<T, E>` where `E: Error + Send + Sync + 'static` into a `LuhTwin<T>`.
///
/// This trait is used when you have errors that don't have `From` implementations defined
/// for `AnyError`, allowing you to manually convert them.
///
/// ## Methods
///
/// ## `fn twin(self) -> LuhTwin<T>`
///
/// Converts a `Result<T, E>` into a `Result<T, AnyError>` by wrapping the error.
/// This is the simplest way to convert foreign error types into your error handling system.
///
/// ## `fn twin_with<F>(self, f: F) -> LuhTwin<T> where F: FnOnce(AnyError) -> AnyError`
///
/// Converts a `Result<T, E>` into a `Result<T, AnyError>` and then passes the `AnyError`
/// through a transformation function. Useful for adding context during the conversion.
///
/// ## Examples
///
/// ```ignore
/// use std::fs::File;
///
/// // Simple conversion
/// fn open_file() -> LuhTwin<File> {
/// File::open("config.json").twin()
/// }
///
/// // With transformation
/// fn open_with_context() -> LuhTwin<File> {
/// File::open("config.json")
/// .twin_with(|e| e.with_context(at!("failed to open config")))
/// }
/// ```