g-err 0.1.0

Structured error type
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
extern crate alloc;

use alloc::boxed::Box;
use alloc::format;
use alloc::string::{String, ToString};
use alloc::vec::Vec;

use crate::gerr_box::GErrBox;
use crate::gerr_source::DataSource;
use crate::gerr_source::GErrSource;
use crate::gerr_source::IdSource;
use crate::types::DefaultConfig;
use crate::types::NoData;

use core::{
    error::Error,
    fmt::{Debug, Display},
    panic::Location,
};

#[cfg(feature = "backtrace")]
use std::backtrace::Backtrace;

use alloc::borrow::Cow;

/// Error config.
pub trait Config {
    /// Error code.
    const CODE: Option<&'static str> = None;

    /// Error id.
    ///
    /// # Must be:
    /// - Implementing `Display` & `Debug`.
    /// - Implementing serde's Serialize and Deserialize for `serde` feature.
    type Id;

    /// Auto-generate error id.
    #[inline]
    fn id() -> Option<Self::Id> {
        None
    }

    /// Display error message.
    ///
    /// It will be invoked in `Display` implementation.
    #[inline]
    fn display<C: Config, D>(gerr: &GErr<C, D>) -> String
    where
        C::Id: Display,
        D: Debug,
    {
        match (gerr.id(), gerr.code()) {
            (Some(id), Some(code)) => format!("[{id}][{code}] {}", gerr.message()),
            (Some(id), None) => format!("[{id}][-] {}", gerr.message()),
            (None, Some(code)) => format!("[-][{code}] {}", gerr.message()),
            (None, None) => format!("[-][-] {}", gerr.message()),
        }
    }
}

/// Trait for upserting error data.
///
/// Self must implement `Default`.
pub trait SetField<K, V> {
    fn set_field(&mut self, key: K, value: V);
}

/// Alias for core's Result.
pub type Result<T, C = DefaultConfig, D = NoData> = core::result::Result<T, GErr<C, D>>;

/// GErr with default config(no id) and no data.
pub type GErrDefault = GErr<DefaultConfig, NoData>;

/// GErr's source
#[derive(Debug)]
pub enum Source {
    /// General error.
    Err(Box<dyn Error + Send + Sync + 'static>),

    // It's boxed to reduce error size.
    /// GErr error.
    GErr(Box<GErrSource>),
}

/// GErr - Structured Error Type.
///
/// It's generically configurable with id, code, data, etc.
///
/// Error location is automatically generated.
///
/// It contains stack-trace if `backtrace` feature is enabled.
///
/// It provides 2 type parameters `C` and `D`:
/// - `C` is for error config. It bounds with [`Config`] trait containing error id and code.
///   - `Id` type: defining error id type.
///   - `id()` function: defining auto-generation function for id.
///   - `CODE` code constant: automatically set error code at construction.
///   - `display` function: for [`Display`] trait.
/// - `D` is for error data.
///
/// GErr contains error as having these attributes:
/// - `id`: The error id. This is to identify the error. It can be autogenerated or from outside(e.g. request id).
/// - `code`: The error code. Acts as label/category/group of errors.
/// - `message`: The error message.
/// - `sources`: The sources of current error. Errors can be linked/chained from multiple errors, serial or parallel.
/// - `tags`: The error tags. Things related to the error. For easy querying.
/// - `data`: The error data. This is additional data about the error. It can be error kinds(enum), user data triggering the errors, etc.
/// - `help`: Hint about how to solve the error.
/// - `location`: Where the error happen.
/// - `backtrace`: The error stacktrace, feature-gated behind `backtrace`.
///
/// # Note
/// Set aside size of error ID and Data:
///
/// - `GErr<DefaultConfig, NoData>` is approximately 160 bytes.
/// - Enabling the `backtrace` feature increases this to approximately
///   208 bytes (+48 bytes from `Backtrace`).
///
/// Clippy's `result_large_err` lint is intentionally allowed for this crate.
/// Users requiring a smaller error representation may box `GErr` in their
/// own APIs or using provided [`GErrBox`].
pub struct GErr<C: Config = DefaultConfig, D = NoData> {
    id: Option<C::Id>,

    code: Option<Cow<'static, str>>,

    message: Cow<'static, str>,

    sources: Option<Vec<Source>>,

    tags: Option<Vec<Cow<'static, str>>>,

    data: Option<D>,

    help: Option<Cow<'static, str>>,

    location: ErrorLocation,

    #[cfg(feature = "backtrace")]
    backtrace: Backtrace,
}

/// Location where error happen.
#[derive(Debug, PartialEq, Eq)]
pub struct ErrorLocation {
    /// Filename of where error happen.
    pub file: Cow<'static, str>,
    /// Line number of where error happen.
    pub line: u32,
    /// Column of where error happen.
    pub column: u32,
}

impl<C: Config, D> GErr<C, D> {
    /// Constructs new GErr with message and auto-generated id.
    #[track_caller]
    #[inline]
    pub fn new<M>(message: M) -> Self
    where
        M: Into<Cow<'static, str>>,
    {
        Self::new_untracked(message, Location::caller())
    }

    #[inline]
    pub(crate) fn new_untracked<M>(message: M, location: &'static Location<'static>) -> Self
    where
        M: Into<Cow<'static, str>>,
    {
        Self::new_with_id_untracked(C::id(), message.into(), location)
    }

    /// Constructs new GErr from any error implementing trait [`Error`]
    ///
    /// Id is auto-generated and only contains message, location and the error as source.
    #[track_caller]
    #[inline]
    pub fn from_error<E>(err: E) -> Self
    where
        E: Error + Send + Sync + 'static,
    {
        Self::new_untracked(err.to_string(), Location::caller()).add_source(err)
    }

    /// Constructs new GErr with id and message.
    ///
    /// This is to set error id manually.
    #[track_caller]
    #[inline]
    pub fn new_with_id<M>(id: C::Id, message: M) -> Self
    where
        M: Into<Cow<'static, str>>,
    {
        Self::new_with_id_untracked(Some(id), message, Location::caller())
    }

    #[inline]
    pub(crate) fn new_with_id_untracked<M>(
        id: Option<C::Id>,
        message: M,
        location: &'static Location<'static>,
    ) -> Self
    where
        M: Into<Cow<'static, str>>,
    {
        Self {
            id,

            code: C::CODE.map(Cow::Borrowed),

            message: message.into(),

            sources: None,

            tags: None,

            data: None,

            help: None,

            location: location.into(),

            #[cfg(feature = "backtrace")]
            backtrace: Backtrace::capture(),
        }
    }

    /// Constructs new GErr from any error implementing trait [`Error`]
    ///
    /// Id is manually-set and only contains message, location and the error as source.
    #[track_caller]
    #[inline]
    pub fn from_error_with_id<E>(id: C::Id, err: E) -> Self
    where
        E: Error + Send + Sync + 'static,
    {
        Self::new_with_id_untracked(Some(id), err.to_string(), Location::caller()).add_source(err)
    }

    #[allow(dead_code)]
    #[inline]
    pub(crate) fn set_location(mut self, loc: ErrorLocation) -> Self {
        self.location = loc;
        self
    }
}

impl<C: Config, D> GErr<C, D> {
    /// Set error id.
    #[must_use]
    #[inline]
    pub fn set_id(mut self, id: C::Id) -> Self {
        self.id = Some(id);
        self
    }

    /// set error code.
    #[must_use]
    #[inline]
    pub fn set_code<T>(mut self, code: T) -> Self
    where
        T: Into<Cow<'static, str>>,
    {
        self.code = Some(code.into());
        self
    }

    /// Set list of sources.
    #[must_use]
    #[inline]
    pub fn set_sources<I>(mut self, sources: I) -> Self
    where
        I: IntoIterator<Item = Source>,
    {
        self.sources = Some(sources.into_iter().collect());
        self
    }

    /// Add general error(non-gerr) into list of sources.
    #[must_use]
    #[inline]
    pub fn add_source<E>(mut self, source: E) -> Self
    where
        E: Error + Send + Sync + 'static,
    {
        self.sources
            .get_or_insert_default()
            .push(Source::Err(Box::new(source)));
        self
    }

    /// Add GErr as error source.
    ///
    /// Any errors implementing `Into<GErrSource>` pass.
    #[inline]
    pub fn add_source_gerr<E>(mut self, gerr: E) -> Self
    where
        E: Into<GErrSource> + Error + Send + Sync + 'static,
    {
        self.sources
            .get_or_insert_default()
            .push(Source::GErr(Box::new(gerr.into())));
        self
    }

    /// Add tag to GErr.
    #[must_use]
    pub fn add_tag<T>(mut self, tag: T) -> Self
    where
        T: Into<Cow<'static, str>>,
    {
        self.tags.get_or_insert_default().push(tag.into());
        self
    }

    /// Add multiple tags at once to GErr.
    #[must_use]
    pub fn add_tags<I, T>(mut self, tags: I) -> Self
    where
        I: IntoIterator<Item = T>,
        T: Into<Cow<'static, str>>,
    {
        let mut tags = tags.into_iter().peekable();
        if tags.peek().is_some() {
            self.tags
                .get_or_insert_default()
                .extend(tags.map(Into::into));
        }
        self
    }

    /// Set error data.
    #[must_use]
    #[inline]
    pub fn set_data(mut self, data: D) -> Self {
        self.data = Some(data);
        self
    }

    /// Set help.
    #[must_use]
    #[inline]
    pub fn set_help<H>(mut self, help: H) -> Self
    where
        H: Into<Cow<'static, str>>,
    {
        self.help = Some(help.into());
        self
    }

    /// Override config type and auto-generate id and code.
    ///
    /// This will overwrite previous id and code with auto-generated ones.
    #[must_use]
    #[inline]
    pub fn with_config<T: Config>(self) -> GErr<T, D> {
        GErr {
            id: T::id(),
            code: T::CODE.map(Cow::Borrowed),
            message: self.message,
            sources: self.sources,
            tags: self.tags,
            data: self.data,
            help: self.help,
            location: self.location,
            #[cfg(feature = "backtrace")]
            backtrace: self.backtrace,
        }
    }

    /// Override Data(D) type.
    #[must_use]
    #[inline]
    pub fn with_data_type<T>(self) -> GErr<C, T> {
        GErr {
            id: self.id,
            code: self.code,
            message: self.message,

            sources: self.sources,

            tags: self.tags,

            data: None,

            help: self.help,

            location: self.location,

            #[cfg(feature = "backtrace")]
            backtrace: self.backtrace,
        }
    }

    /// Override Data(D) value and type.
    ///
    /// This returns new GErr with different type of Data.
    #[must_use]
    #[inline]
    pub fn with_data<T>(self, data: T) -> GErr<C, T> {
        GErr {
            id: self.id,
            message: self.message,

            code: self.code,
            sources: self.sources,

            tags: self.tags,

            data: Some(data),

            help: self.help,

            location: self.location,

            #[cfg(feature = "backtrace")]
            backtrace: self.backtrace,
        }
    }

    // --- getter ---

    /// Error id.
    #[inline]
    pub fn id(&self) -> Option<&C::Id> {
        self.id.as_ref()
    }

    /// Error message.
    #[inline]
    pub fn message(&self) -> &str {
        &self.message
    }

    /// Error code.
    #[inline]
    pub fn code(&self) -> Option<&str> {
        self.code.as_deref().or(C::CODE)
    }

    /// Error tags.
    #[inline]
    pub fn tags(&self) -> Option<&[Cow<'static, str>]> {
        self.tags.as_deref()
    }

    /// Iterate over tags.
    #[inline]
    pub fn iter_tags(&self) -> impl Iterator<Item = &str> {
        self.tags.iter().flatten().map(Cow::as_ref)
    }

    /// Error data.
    #[inline]
    pub fn data(&self) -> Option<&D> {
        self.data.as_ref()
    }

    /// Error sources.
    #[inline]
    pub fn sources(&self) -> Option<&[Source]> {
        self.sources.as_deref()
    }

    /// Error location.
    #[inline]
    pub fn location(&self) -> &ErrorLocation {
        &self.location
    }

    /// Error help hint.
    #[inline]
    pub fn help(&self) -> Option<&str> {
        self.help.as_deref()
    }

    /// Error stacktrace, if `backtrace` enabled.
    #[cfg(feature = "backtrace")]
    #[inline]
    pub fn backtrace(&self) -> &std::backtrace::Backtrace {
        &self.backtrace
    }

    /// Returns GErr as `Result<T, GErr<ID, P, D>>`.
    #[inline]
    pub fn result<T>(self) -> Result<T, C, D> {
        Result::Err(self)
    }

    /// Box GErr
    #[inline]
    pub fn boxed(self) -> GErrBox<C, D> {
        Box::new(self)
    }
}

impl<C: Config, D> GErr<C, D> {
    /// Update error data's fields provided that the data implement `Default` and [`SetField`].
    ///
    /// [`SetField`] trait implementation is user-defined.
    #[must_use]
    #[inline]
    pub fn set_field<K, V>(mut self, key: K, value: V) -> Self
    where
        D: Default + SetField<K, V>,
    {
        let data = self.data.get_or_insert_with(Default::default);
        data.set_field(key, value);
        self
    }
}

impl<C: Config, D> Display for GErr<C, D>
where
    C::Id: Display,
    D: Debug,
{
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "{}", C::display(self))
    }
}

impl<C: Config, D: Debug> Debug for GErr<C, D>
where
    C::Id: Debug,
{
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        let mut debug = f.debug_struct("GErr");

        debug
            .field("id", &self.id)
            .field("code", &self.code())
            .field("message", &self.message)
            .field("sources", &self.sources)
            .field("tags", &self.tags)
            .field("data", &self.data)
            .field("help", &self.help())
            .field("location", &self.location);

        #[cfg(feature = "backtrace")]
        debug.field("backtrace", &self.backtrace);

        debug.finish()
    }
}

impl<C: Config, D> Error for GErr<C, D>
where
    C::Id: Debug + Display,
    D: Debug,
{
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        if let Some(ref sources) = self.sources
            && !sources.is_empty()
        {
            return sources.first().map(|s| match s {
                Source::Err(e) => &**e as &(dyn Error + 'static),
                Source::GErr(e) => &**e as &(dyn Error + 'static),
            });
        }
        None
    }
}

#[cfg(not(feature = "serde"))]
impl<C: Config, D> From<GErr<C, D>> for GErrSource
where
    C::Id: IdSource + 'static,
    D: DataSource + 'static,
{
    fn from(gerr: GErr<C, D>) -> Self {
        GErrSource {
            id: gerr.id.map(|id| Box::new(id) as Box<dyn IdSource>),
            code: gerr.code,
            message: gerr.message,
            tags: gerr.tags,
            data: gerr.data.map(|d| Box::new(d) as Box<dyn DataSource>),
            help: gerr.help,
            location: Some(gerr.location),
            sources: gerr.sources,
        }
    }
}

#[cfg(not(feature = "serde"))]
impl<C: Config, D> GErr<C, D>
where
    C::Id: IdSource + 'static,
    D: DataSource + 'static,
{
    /// Converts GErr into [`GErrSource`].
    #[inline]
    pub fn into_gerr_source(self) -> GErrSource {
        self.into()
    }
}

#[cfg(feature = "serde")]
impl<C: Config, D> From<GErr<C, D>> for GErrSource
where
    C::Id: ::serde::Serialize + IdSource + 'static,
    D: ::serde::Serialize + DataSource + 'static,
{
    fn from(gerr: GErr<C, D>) -> Self {
        GErrSource {
            id_json: gerr
                .id()
                .map(|id| serde_json::to_value(id).unwrap_or_default()),
            id: gerr.id.map(|id| Box::new(id) as Box<dyn IdSource>),
            code: gerr.code,
            message: gerr.message,
            tags: gerr.tags,
            data_json: gerr
                .data
                .as_ref()
                .map(|d| serde_json::to_value(d).unwrap_or_default()),
            data: gerr.data.map(|d| Box::new(d) as Box<dyn DataSource>),
            help: gerr.help,
            location: Some(gerr.location),
            sources: gerr.sources,
        }
    }
}

#[cfg(feature = "serde")]
impl<C: Config, D> GErr<C, D>
where
    C::Id: ::serde::Serialize + IdSource + 'static,
    D: ::serde::Serialize + DataSource + 'static,
{
    /// Converts GErr into [`GErrSource`].
    #[inline]
    pub fn into_gerr_source(self) -> GErrSource {
        self.into()
    }
}

impl<T, C: Config, D> From<GErr<C, D>> for core::result::Result<T, GErr<C, D>> {
    #[inline]
    fn from(value: GErr<C, D>) -> Self {
        core::result::Result::Err(value)
    }
}

impl From<&'static core::panic::Location<'static>> for ErrorLocation {
    #[inline]
    fn from(location: &'static core::panic::Location<'static>) -> Self {
        Self {
            file: Cow::Borrowed(location.file()),
            line: location.line(),
            column: location.column(),
        }
    }
}