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
#![cfg_attr(nightly, feature(error_generic_member_access))]
use std::{
    any::Any,
    borrow::Cow,
    fmt::{self, Debug, Display},
    str::FromStr,
};

use mdsn::DsnError;
use source::Inner;
use thiserror::Error;

mod code;
mod source;

pub use code::Code;

/// The `Error` type, a wrapper around raw libtaos.so client errors or
/// dynamic error types that could be integrated into [anyhow::Error].
///
/// # Constructions
///
/// We prefer to use [format_err] to construct errors, but you can always use
/// constructor API in your codes.
///
/// ## Constructor API
///
/// Use error code from native client. You can use it directly with error code
///
/// ```rust
/// # use taos_error::Error;
/// let error = Error::from_code(0x2603);
/// ```
///
/// Or with error message from C API.
///
/// ```rust
/// # use taos_error::Error;
/// let error = Error::new(0x0216, r#"syntax error near "123);""#); // Syntax error in SQL
/// ```
///
/// # Display representations
#[derive(Error)]
#[must_use]
pub struct Error {
    /// Error code, will be displayed when code is not 0xFFFF.
    code: Code,
    /// Error context, use this along with `.msg` or `.source`.
    context: Option<String>,
    /// Error source, from raw or other error type.
    #[cfg_attr(nightly, backtrace)]
    source: Inner,
}

unsafe impl Send for Error {}
unsafe impl Sync for Error {}

impl Debug for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if f.alternate() {
            f.debug_struct("Error")
                .field("code", &self.code)
                .field("context", &self.context)
                .field("source", &self.source)
                .finish()
        } else {
            // Error code prefix
            if self.code != Code::FAILED {
                write!(f, "[{:#06X}] ", self.code)?;
            }
            if let Some(context) = &self.context {
                f.write_fmt(format_args!("{}", context))?;
                writeln!(f)?;
                writeln!(f)?;
                writeln!(f, "Caused by:")?;

                let chain = self.source.chain();
                for (idx, source) in chain.enumerate() {
                    writeln!(f, "{:4}: {}", idx, source)?;
                }
            } else {
                let mut chain = self.source.chain();
                if let Some(context) = chain.next() {
                    f.write_fmt(format_args!("{}", context))?;
                }

                if self.source.deep() {
                    writeln!(f)?;
                    writeln!(f)?;
                    writeln!(f, "Caused by:")?;
                    for (idx, source) in chain.enumerate() {
                        writeln!(f, "{:4}: {}", idx, source)?;
                    }
                }
            }
            #[cfg(nightly)]
            {
                writeln!(f)?;
                writeln!(f, "Backtrace:")?;
                writeln!(f, "{}", self.source.backtrace())?;
            }

            Ok(())
        }
    }
}

impl Display for Error {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // Error code prefix
        if self.code != Code::FAILED {
            write!(f, "[{:#06X}] ", self.code)?;
        }
        // Error context
        if let Some(context) = self.context.as_deref() {
            write!(f, "{}", context)?;

            if self.source.is_empty() {
                return Ok(());
            }
            // pretty print error source.
            f.write_str(": ")?;
        } else if self.source.is_empty() {
            return f.write_str("Unknown error");
        }

        if f.alternate() {
            write!(f, "{:#}", self.source)?;
        } else {
            write!(f, "{}", self.source)?;
        }
        Ok(())
    }
}

impl From<DsnError> for Error {
    fn from(dsn: DsnError) -> Self {
        Self::new(Code::FAILED, dsn.to_string())
    }
}

impl From<anyhow::Error> for Error {
    fn from(error: anyhow::Error) -> Self {
        Self {
            code: Code::FAILED,
            context: None,
            source: Inner::any(error),
        }
    }
}

impl<C: Into<Code>> From<C> for Error {
    fn from(value: C) -> Self {
        Self::from_code(value.into())
    }
}

impl<'a> From<&'a str> for Error {
    fn from(value: &'a str) -> Self {
        Self::from_string(value.to_string())
    }
}

pub type Result<T> = std::result::Result<T, Error>;

impl Error {
    #[inline(always)]
    pub fn new_with_context(
        code: impl Into<Code>,
        err: impl Into<String>,
        context: impl Into<String>,
    ) -> Self {
        Self {
            code: code.into(),
            context: Some(context.into()),
            source: err.into().into(),
        }
    }
    #[inline]
    pub fn new(code: impl Into<Code>, err: impl Into<String>) -> Self {
        Self {
            code: code.into(),
            context: None,
            source: err.into().into(),
        }
    }

    #[inline]
    pub fn context(mut self, context: impl Into<String>) -> Self {
        self.context = Some(match self.context {
            Some(pre) => format!("{}: {}", context.into(), pre),
            None => context.into(),
        });
        self
    }

    #[inline]
    #[deprecated = "Use self.code() instead"]
    pub fn errno(&self) -> Code {
        self.code
    }

    #[inline]
    pub const fn code(&self) -> Code {
        self.code
    }
    #[inline]
    pub fn message(&self) -> String {
        self.source.to_string()
    }

    #[inline(always)]
    pub fn from_code(code: impl Into<Code>) -> Self {
        let code = code.into();
        if let Some(str) = code._priv_err_str() {
            Self::new(code, str)
        } else {
            Self {
                code,
                context: None,
                source: Inner::empty(),
            }
        }
    }

    #[inline]
    pub fn from_string(err: impl Into<Cow<'static, str>>) -> Self {
        anyhow::format_err!("{}", err.into()).into()
    }

    #[inline]
    pub fn from_any(err: impl Into<anyhow::Error>) -> Self {
        err.into().into()
    }

    #[inline]
    pub fn any(err: impl Into<anyhow::Error> + 'static) -> Self {
        if err.type_id() == std::any::TypeId::of::<Self>() {
            // let err = Box::new(&err as &dyn Any);
            let err = &err as &dyn Any;
            let err = err.downcast_ref::<Self>().unwrap();
            dbg!(err);
            return Self {
                code: err.code,
                context: err.context.clone(),
                source: err.source.clone(),
            };
        }
        err.into().into()
    }

    #[inline]
    pub fn success(&self) -> bool {
        self.code == 0
    }
}

/// Format error with `code`, `raw`, and `context` messages.
///
/// - `code` is come from native C API for from websocket API.
/// - `raw` is the error message which is treated as internal error.
/// - `context` is some context message which is helpful to users.
///
/// We suggest to use all the three fields to construct a more human-readable and
/// meaningful error. Suck as:
///
/// ```rust
/// # use taos_error::*;
/// let err = format_err!(
///     code = 0x0618,
///     raw = "Message error from native API",
///     context = "Query with sql: `select server_status()`"
/// );
/// let err_str = err.to_string();
/// assert_eq!(err_str, "[0x0618] Query with sql: `select server_status()`: Internal error: `Message error from native API`");
/// ```
///
/// It will give the error:
/// ```text
/// [0x0618] Query with sql: `select server_status()`: Internal error: `Message error from native API`
/// ```
///
/// For more complex error expressions, use a `format!` like API as this:
///
/// ```rust
/// # use taos_error::*;
/// # let sql = "select * from test.meters";
/// # let context = "some context";
/// let _ = format_err!(
///     code = 0x0618,
///     raw = ("Message error from native API while calling {}", "some_c_api"),
///     context = ("Query with sql {:?} in {}", sql, context),
/// );
/// ```
///
/// In this kind of usage, `code = ` is optional, so you can use a shorter line:
///
/// ```rust
/// # use taos_error::*;
/// let _ = format_err!(0x0618, raw = "Some error", context = "Query error");
/// ```
///
/// The `raw` or `context` is optional too:
///
/// ```rust
/// # use taos_error::*;
/// let _ = format_err!(0x0618, raw = "Some error");
/// let _ = format_err!(0x0618, context = "Some error");
/// ```
///
/// For non-internal errors, eg. if you prefer construct an [anyhow]-like error manually,
/// you can use the same arguments like [anyhow::format_err] with this pattern:
///
/// ```rust
/// # use taos_error::*;
/// # let message = "message";
/// let err = format_err!(any = "Error here: {}", message);
/// # assert_eq!(err.to_string(), "Error here: message");
/// let err = format_err!("Error here: {}", message);
/// # assert_eq!(err.to_string(), "Error here: message");
/// ```
///
/// It's equivalent to:
///
/// ```rust
/// # use taos_error::*;
/// # use anyhow;
/// # let message = "message";
/// let err = Error::from(anyhow::format_err!("Error here: {}", message));
/// ```
///
#[macro_export]
macro_rules! format_err {
    (code = $c:expr, raw = $arg:expr, context = $arg2:expr) => {
        $crate::Error::new_with_context($c, $arg, $arg2)
    };
    (code = $c:expr, raw = $arg:expr) => {
        $crate::Error::new($c, $arg)
    };
    (code = $c:expr, raw = ($($arg:tt)*), context = ($($arg2:tt)*) $(,)?) => {
        $crate::Error::new_with_context($c, __priv_format!($($arg)*), __priv_format!($($arg2)*))
    };
    (code = $c:expr, context = $($arg2:tt)*) => {
        $crate::Error::from($c).context(format!($($arg2)*))
    };
    // // (code = $c:expr, raw = $arg:literal, context = $arg2:literal) => {
    // //     $crate::Error::new_with_context($c, format!($arg), format!($arg2))
    // // };
    // // (code = $c:expr, raw = $arg:literal, context = $arg2:expr) => {
    // //     $crate::Error::new_with_context($c, format!($arg), $arg2)
    // // };
    (code = $c:expr, raw = $arg:literal, context = $($arg2:tt)*) => {
        $crate::Error::new_with_context($c, format!($arg), $crate::__priv_format!($($arg2)*))
    };
    (code = $c:expr, raw = $arg:ident, context = $($arg2:tt)*) => {
        $crate::Error::new_with_context($c, $arg, $crate::__priv_format!($($arg2)*))
    };
    (code = $c:expr) => {
        $crate::Error::from_code($c)
    };
    (code = $c:expr, raw = $($arg:tt)*) => {
        $crate::Error::new($c, format!($($arg)*))
    };
    (code = $c:expr, $($arg:tt)*) => {
        $crate::Error::new($c, format!($($arg)*))
    };
    (any = $($arg:tt)*) => {
        $crate::Error::from_string(format!($($arg)*))
    };
    (raw = $($arg:tt)*) => {
        compile_error!("`raw` error message must be used along with an error code!")
    };

    ($c:expr, raw = $arg:expr) => {
        $crate::Error::new($c, $arg)
    };
    ($c:expr, raw = $arg:expr, context = $arg2:expr) => {
        $crate::Error::new_with_context($c, $arg, $arg2)
    };
    ($c:expr, raw = ($($arg:tt)*), context = ($($arg2:tt)*) $(,)?) => {
        $crate::Error::new_with_context($c, format!($($arg)*), format!($($arg2)*))
    };
    ($c:expr, context = $arg:expr) => {
        $crate::Error::from($c).context($arg)
    };
    ($c:expr, context = $($arg2:tt)*) => {
        $crate::Error::from($c).context(format!($($arg2)*))
    };
    ($c:expr, raw = $($arg:tt)*) => {
        $crate::Error::new($c, format!($($arg)*))
    };
    ($c:expr) => {
        $crate::Error::from($c)
    };
    ($($arg:tt)*) => {
        $crate::Error::from_string(format!($($arg)*))
    };
}
#[macro_export]
macro_rules! __priv_format {
    ($msg:literal $(,)?) => {
        literal.to_string()
    };
    ($err:expr $(,)?) => {
        $err
    };
    ($fmt:expr, $($arg:tt)*) => {
        format!($fmt, $($arg)*)
    };
}

#[macro_export]
macro_rules! bail {
    ($($arg:tt)*) => {
        return std::result::Result::Err($crate::format_err!($($arg)*))
    };
}

impl FromStr for Error {
    type Err = ();

    #[inline]
    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
        Ok(Self::from_string(s.to_string()))
    }
}

#[cfg(feature = "serde")]
impl serde::de::Error for Error {
    #[inline]
    fn custom<T: fmt::Display>(msg: T) -> Error {
        Error::from_string(format!("{}", msg))
    }
}

#[test]
fn test_format_err() {
    let code = 0xF000;
    let raw = "Nothing";
    let context = "Error";
    let err = dbg!(format_err!(code, raw = raw, context = context));
    assert_eq!(err.to_string(), "[0xF000] Error: Internal error: `Nothing`");
    let err = dbg!(format_err!(code, raw = raw));
    assert_eq!(err.to_string(), "[0xF000] Internal error: `Nothing`");
    let err = dbg!(format_err!(code, context = context));
    assert_eq!(err.to_string(), "[0xF000] Error");

    let err = dbg!(format_err!(code = 0xF000, context = "Error here"));
    assert_eq!(err.to_string(), "[0xF000] Error here");
    let err = dbg!(format_err!(0x6789, context = "Error here: {}", 1));
    assert_eq!(err.to_string(), "[0x6789] Error here: 1");
    let err = dbg!(format_err!(code = 0x6789, context = "Error here: {}", 1));
    assert_eq!(err.to_string(), "[0x6789] Error here: 1");

    let err = dbg!(format_err!(code = 0x6789, raw = "Error here: {}", 1));
    assert_eq!(err.to_string(), "[0x6789] Internal error: `Error here: 1`");

    let err = dbg!(format_err!(0x6789, raw = "Error here: {}", 1));
    assert_eq!(err.to_string(), "[0x6789] Internal error: `Error here: 1`");

    let err = dbg!(format_err!(
        code = 0x6789,
        raw = ("Error here: {}", 1),
        context = ("Query error with {:?}", "sql"),
    ));
    assert_eq!(
        err.to_string(),
        "[0x6789] Query error with \"sql\": Internal error: `Error here: 1`"
    );

    let err = dbg!(format_err!("Error here"));
    assert_eq!(err.to_string(), "Error here");

    let err = dbg!(format_err!(0x2603));
    assert_eq!(
        err.to_string(),
        "[0x2603] Internal error: `Table does not exist`"
    );

    let err = dbg!(format_err!(0x6789));
    assert_eq!(err.to_string(), "[0x6789] Unknown error");

    let err = dbg!(format_err!(0x6789, context = "Error here"));
    assert_eq!(err.to_string(), "[0x6789] Error here");
}

#[test]
fn test_bail() {
    fn use_bail() -> Result<()> {
        bail!(code = 0x2603, context = "Failed to insert into table `abc`");
    }
    let err = use_bail();
    dbg!(&err);
    assert!(err.is_err());
    println!("{:?}", err.unwrap_err());

    println!("{:?}", Error::any(use_bail().unwrap_err()));
}

#[test]
fn test_display() {
    let err = Error::new(Code::SUCCESS, "Success").context("nothing");
    assert!(dbg!(format!("{}", err)).contains("[0x0000] nothing"));
    let result = std::panic::catch_unwind(|| {
        let err = Error::new(Code::SUCCESS, "Success").context("nothing");
        panic!("{:?}", err);
    });
    assert!(result.is_err());
}

#[test]
fn test_error() {
    let err = Error::new(Code::SUCCESS, "success");
    assert_eq!(err.code(), Code::SUCCESS);
    assert_eq!(err.message(), "Internal error: `success`");

    let _ = Error::from_code(1);
    assert_eq!(Error::from_string("any").to_string(), "any");
    assert_eq!(Error::from_string("any").to_string(), "any");

    fn raise_error() -> Result<()> {
        Err(Error::from_any(DsnError::InvalidDriver("mq".to_string())))
    }
    assert_eq!(raise_error().unwrap_err().to_string(), "invalid driver mq");
}

#[cfg(feature = "serde")]
#[test]
fn test_serde_error() {
    use serde::de::Error as DeError;

    let _ = Error::custom("");
}