rustic_rs/
error.rs

1//! Error types
2
3use abscissa_core::error::{BoxError, Context};
4#[cfg(feature = "rhai")]
5use rhai::EvalAltResult;
6use std::{
7    fmt::{self, Display},
8    io,
9    ops::Deref,
10};
11use thiserror::Error;
12
13/// Kinds of errors
14#[derive(Clone, Debug, Eq, Error, PartialEq)]
15pub(crate) enum ErrorKind {
16    /// Input/output error
17    #[error("I/O error")]
18    Io,
19}
20
21/// Kinds of [`rhai`] errors
22#[cfg(feature = "rhai")]
23#[derive(Debug, Error)]
24pub(crate) enum RhaiErrorKinds {
25    #[error(transparent)]
26    RhaiParse(#[from] rhai::ParseError),
27    #[error(transparent)]
28    RhaiEval(#[from] Box<EvalAltResult>),
29}
30
31impl ErrorKind {
32    /// Create an error context from this error
33    pub(crate) fn context(self, source: impl Into<BoxError>) -> Context<Self> {
34        Context::new(self, Some(source.into()))
35    }
36}
37
38/// Error type
39#[derive(Debug)]
40pub(crate) struct Error(Box<Context<ErrorKind>>);
41
42impl Deref for Error {
43    type Target = Context<ErrorKind>;
44
45    fn deref(&self) -> &Context<ErrorKind> {
46        &self.0
47    }
48}
49
50impl Display for Error {
51    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
52        self.0.fmt(f)
53    }
54}
55
56impl std::error::Error for Error {
57    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
58        self.0.source()
59    }
60}
61
62impl From<ErrorKind> for Error {
63    fn from(kind: ErrorKind) -> Self {
64        Context::new(kind, None).into()
65    }
66}
67
68impl From<Context<ErrorKind>> for Error {
69    fn from(context: Context<ErrorKind>) -> Self {
70        Self(Box::new(context))
71    }
72}
73
74impl From<io::Error> for Error {
75    fn from(err: io::Error) -> Self {
76        ErrorKind::Io.context(err).into()
77    }
78}