sqlite_tiny/
error.rs

1//! Implements the crate's error type
2#![cfg(feature = "api")]
3
4use std::backtrace::{Backtrace, BacktraceStatus};
5use std::fmt::{self, Display, Formatter};
6
7/// Creates a new error
8#[macro_export]
9macro_rules! err {
10    (with: $error:expr, $($arg:tt)*) => {{
11        let error = format!($($arg)*);
12        let source = Box::new($error);
13        $crate::error::Error::new(error, Some(source))
14    }};
15    ($($arg:tt)*) => {{
16        let error = format!($($arg)*);
17        $crate::error::Error::new(error, None)
18    }};
19}
20
21/// The crates error type
22#[derive(Debug)]
23pub struct Error {
24    /// The error description
25    pub error: String,
26    /// The underlying error
27    pub source: Option<Box<dyn std::error::Error + Send>>,
28    /// The backtrace
29    pub backtrace: Backtrace,
30}
31impl Error {
32    /// Creates a new error and captures a backtrace
33    pub fn new(error: String, source: Option<Box<dyn std::error::Error + Send>>) -> Self {
34        let backtrace = Backtrace::capture();
35        Self { error, source, backtrace }
36    }
37
38    /// Whether the error has captured a backtrace or not
39    pub fn has_backtrace(&self) -> bool {
40        self.backtrace.status() == BacktraceStatus::Captured
41    }
42}
43impl Display for Error {
44    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
45        // Print the error
46        writeln!(f, "{}", self.error)?;
47
48        // Print the source
49        if let Some(source) = &self.source {
50            writeln!(f, " caused by: {source}")?;
51        }
52        Ok(())
53    }
54}
55impl std::error::Error for Error {
56    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
57        // Do some type gymnastics to get the `Send` out of the typesystem, because it breaks a direct conversion
58        #[allow(clippy::borrowed_box, reason = "Type gymnastics to remove the `Send`")]
59        let source: &Box<dyn std::error::Error + Send> = self.source.as_ref()?;
60        let source: &dyn std::error::Error = source.as_ref();
61        Some(source)
62    }
63}