ntex-error 2.2.0

ntex error management
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
use std::{error, fmt, fmt::Write, rc::Rc};

use ntex_bytes::ByteString;

use crate::{AsError, ErrorDiagnostic, ResultType};

struct Wrt<'a> {
    written: usize,
    fmt: &'a mut dyn fmt::Write,
}

impl<'a> Wrt<'a> {
    fn new(fmt: &'a mut dyn fmt::Write) -> Self {
        Wrt { fmt, written: 0 }
    }

    fn wrote(&mut self) -> bool {
        let res = self.written != 0;
        self.written = 0;
        res
    }
}

impl fmt::Write for Wrt<'_> {
    fn write_str(&mut self, s: &str) -> Result<(), fmt::Error> {
        self.written += s.len();
        self.fmt.write_str(s)
    }

    fn write_char(&mut self, c: char) -> Result<(), fmt::Error> {
        self.written += 1;
        self.fmt.write_char(c)
    }
}

pub fn fmt_err_string(e: &dyn error::Error) -> String {
    let mut buf = String::new();
    _ = fmt_err(&mut buf, e);
    buf
}

pub fn fmt_err(f: &mut dyn fmt::Write, e: &dyn error::Error) -> fmt::Result {
    let mut wrt = Wrt::new(f);
    let mut current = Some(e);
    while let Some(std_err) = current {
        write!(&mut wrt, "{std_err}")?;
        if wrt.wrote() {
            writeln!(wrt.fmt)?;
        }
        current = std_err.source();
    }
    Ok(())
}

/// Formats a full diagnostic view of an error for logging and tracing.
pub fn fmt_diag_string<'a, T>(e: &'a T) -> String
where
    T: ErrorDiagnostic + AsError,
    ResultType: From<&'a T::Target>,
{
    let mut buf = String::new();
    _ = fmt_diag(&mut buf, e);
    buf
}

/// Formats a full diagnostic view of an error for logging and tracing.
///
/// For `ServiceError` types, this includes debug representations of all nested errors,
/// and a backtrace when available.
pub fn fmt_diag<'a, T>(f: &mut dyn fmt::Write, container: &'a T) -> fmt::Result
where
    T: ErrorDiagnostic + AsError,
    ResultType: From<&'a T::Target>,
{
    fmt_diag_typ(f, Some(ResultType::from(container.as_diag())), container)
}

/// Formats a full diagnostic view of an error for logging and tracing.
///
/// For `ServiceError` types, this includes debug representations of all nested errors,
/// and a backtrace when available.
pub fn fmt_diag_typ<T>(
    f: &mut dyn fmt::Write,
    typ: Option<ResultType>,
    e: &T,
) -> fmt::Result
where
    T: ErrorDiagnostic,
{
    writeln!(f, "err: {e}")?;
    if let Some(ref tp) = typ {
        writeln!(f, "type: {}", tp.as_str())?;
    }
    writeln!(f, "signature: {}", e.signature())?;

    if let Some(tag) = e.tag() {
        if let Ok(s) = ByteString::try_from(tag) {
            writeln!(f, "tag: {s}")?;
        } else {
            writeln!(f, "tag: {tag:?}")?;
        }
    }
    if let Some(svc) = e.service() {
        writeln!(f, "service: {svc}")?;
    }
    writeln!(f)?;

    let mut wrt = Wrt::new(f);
    write!(&mut wrt, "{e:?}")?;
    if wrt.wrote() {
        writeln!(wrt.fmt)?;
    }

    let mut current = e.source();
    while let Some(err) = current {
        write!(&mut wrt, "{err:?}")?;
        if wrt.wrote() {
            writeln!(wrt.fmt)?;
        }
        current = err.source();
    }

    if typ == Some(ResultType::ServiceError)
        && let Some(bt) = e.backtrace()
        && let Some(repr) = bt.repr()
    {
        writeln!(wrt.fmt, "{repr}")?;
    }

    Ok(())
}

#[derive(Clone, PartialEq, Eq, thiserror::Error)]
pub struct ErrorMessage(ByteString);

#[derive(Clone)]
pub struct ErrorMessageChained {
    msg: ByteString,
    source: Option<Rc<dyn error::Error>>,
}

impl ErrorMessageChained {
    pub fn new<M, E>(ctx: M, source: E) -> Self
    where
        M: Into<ErrorMessage>,
        E: error::Error + 'static,
    {
        ErrorMessageChained {
            msg: ctx.into().into_string(),
            source: Some(Rc::new(source)),
        }
    }

    /// Construct `ErrorMessageChained` from `ByteString`
    pub const fn from_bstr(msg: ByteString) -> Self {
        Self { msg, source: None }
    }

    pub fn msg(&self) -> &ByteString {
        &self.msg
    }
}

impl ErrorMessage {
    /// Construct a new empty `ErrorMessage`
    pub const fn empty() -> Self {
        Self(ByteString::from_static(""))
    }

    /// Construct `ErrorMessage` from `ByteString`
    pub const fn from_bstr(msg: ByteString) -> ErrorMessage {
        ErrorMessage(msg)
    }

    /// Construct `ErrorMessage` from static string
    pub const fn from_static(msg: &'static str) -> Self {
        ErrorMessage(ByteString::from_static(msg))
    }

    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    pub fn as_str(&self) -> &str {
        &self.0
    }

    pub fn as_bstr(&self) -> &ByteString {
        &self.0
    }

    pub fn into_string(self) -> ByteString {
        self.0
    }

    pub fn with_source<E: error::Error + 'static>(self, source: E) -> ErrorMessageChained {
        ErrorMessageChained::new(self, source)
    }
}

impl From<String> for ErrorMessage {
    fn from(value: String) -> Self {
        Self(ByteString::from(value))
    }
}

impl From<ByteString> for ErrorMessage {
    fn from(value: ByteString) -> Self {
        Self(value)
    }
}

impl From<&'static str> for ErrorMessage {
    fn from(value: &'static str) -> Self {
        Self(ByteString::from_static(value))
    }
}

impl fmt::Debug for ErrorMessage {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(&self.0, f)
    }
}

impl fmt::Display for ErrorMessage {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(&self.0, f)
    }
}

impl From<ErrorMessage> for ByteString {
    fn from(msg: ErrorMessage) -> Self {
        msg.0
    }
}

impl<'a> From<&'a ErrorMessage> for ByteString {
    fn from(msg: &'a ErrorMessage) -> Self {
        msg.0.clone()
    }
}

impl<M: Into<ErrorMessage>> From<M> for ErrorMessageChained {
    fn from(value: M) -> Self {
        ErrorMessageChained {
            msg: value.into().0,
            source: None,
        }
    }
}

impl error::Error for ErrorMessageChained {
    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
        self.source.as_ref().map(AsRef::as_ref)
    }
}

impl fmt::Debug for ErrorMessageChained {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(&self, f)
    }
}

impl fmt::Display for ErrorMessageChained {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.msg.is_empty() {
            Ok(())
        } else {
            fmt::Display::fmt(&self.msg, f)
        }
    }
}

#[cfg(test)]
#[allow(dead_code)]
mod tests {
    use ntex_bytes::Bytes;
    use std::{error::Error, io};

    use super::*;

    #[test]
    fn error_message() {
        let msg = ErrorMessage::empty();
        assert!(msg.is_empty());
        assert_eq!(msg.as_str(), "");
        assert_eq!(msg.as_bstr(), ByteString::new());
        assert_eq!(ByteString::new(), msg.as_bstr());
        assert_eq!(ByteString::new(), msg.into_string());

        let msg = ErrorMessage::from("test");
        assert!(!msg.is_empty());
        assert_eq!(format!("{msg}"), "test");
        assert_eq!(format!("{msg:?}"), "test");
        assert_eq!(msg.as_str(), "test");
        assert_eq!(msg.as_bstr(), ByteString::from("test"));

        let msg = ErrorMessage::from("test".to_string());
        assert!(!msg.is_empty());
        assert_eq!(msg.as_str(), "test");
        assert_eq!(msg.as_bstr(), ByteString::from("test"));

        let msg = ErrorMessage::from_bstr(ByteString::from("test"));
        assert!(!msg.is_empty());
        assert_eq!(msg.as_str(), "test");
        assert_eq!(msg.as_bstr(), ByteString::from("test"));

        let msg = ErrorMessage::from(ByteString::from("test"));
        assert!(!msg.is_empty());
        assert_eq!(msg.as_str(), "test");
        assert_eq!(msg.as_bstr(), ByteString::from("test"));

        let msg = ErrorMessage::from_static("test");
        assert!(!msg.is_empty());
        assert_eq!(msg.as_str(), "test");
        assert_eq!(msg.as_bstr(), ByteString::from("test"));

        assert_eq!(ByteString::from(&msg), "test");
        assert_eq!(ByteString::from(msg), "test");
    }

    #[test]
    fn error_message_chained() {
        let chained = ErrorMessageChained::from(ByteString::from("test"));
        assert_eq!(chained.msg(), "test");
        assert!(chained.source().is_none());

        let chained = ErrorMessageChained::from_bstr(ByteString::from("test"));
        assert_eq!(chained.msg(), "test");
        assert!(chained.source().is_none());
        assert_eq!(format!("{chained}"), "test");
        assert_eq!(format!("{chained:?}"), "test");

        let msg = ErrorMessage::from(ByteString::from("test"));
        let chained = msg.with_source(io::Error::other("io-test"));
        assert_eq!(chained.msg(), "test");
        assert!(chained.source().is_some());

        let err = ErrorMessageChained::new("test", io::Error::other("io-test"));
        let msg = fmt_err_string(&err);
        assert_eq!(msg, "test\nio-test\n");

        let chained = ErrorMessageChained::from(ByteString::new());
        assert_eq!(format!("{chained}"), "");
    }

    #[derive(thiserror::Error, derive_more::Debug)]
    enum TestError {
        #[error("Disconnect")]
        #[debug("")]
        Disconnect(#[source] io::Error),
        #[error("InternalServiceError")]
        #[debug("InternalServiceError {_0}")]
        Service(&'static str),
    }

    impl Clone for TestError {
        fn clone(&self) -> Self {
            panic!()
        }
    }

    impl ErrorDiagnostic for TestError {
        fn signature(&self) -> &'static str {
            match self {
                TestError::Service(_) => ResultType::ServiceError.as_str(),
                TestError::Disconnect(_) => ResultType::ClientError.as_str(),
            }
        }
    }

    impl From<&TestError> for ResultType {
        fn from(err: &TestError) -> ResultType {
            match err {
                TestError::Service(_) => ResultType::ServiceError,
                TestError::Disconnect(_) => ResultType::ClientError,
            }
        }
    }

    #[test]
    fn fmt_diag() {
        let err = TestError::Service("409 Error");

        let msg = fmt_err_string(&err);
        assert_eq!(msg, "InternalServiceError\n");

        let err =
            crate::Error::from(TestError::Disconnect(io::Error::other("Test io error")));
        if let Some(bt) = err.backtrace() {
            bt.resolver().resolve();
        }
        let msg = fmt_diag_string(&err);
        assert!(msg.contains("Test io error"), "{msg}");

        assert!(
            format!("{:?}", err.source()).contains("Test io erro"),
            "{:?}",
            err.source().unwrap()
        );

        let err = err.set_tag(Bytes::from("test-tag"));
        let msg = fmt_diag_string(&err);
        assert!(msg.contains("test-tag"), "{msg}");
    }
}