Skip to main content

kardia_core/
error.rs

1use std::error::Error as StdError;
2use std::fmt;
3use std::sync::Arc;
4
5use crate::key::Key;
6
7/// A cheaply clonable, type-erased error.
8///
9/// Every `std::error::Error` converts into it, so plugin code can use `?` on
10/// any fallible call. It deliberately does not implement `std::error::Error`
11/// itself (that would conflict with the blanket `From`); use [`Error::as_std`]
12/// where a standard error is required.
13#[derive(Clone)]
14pub struct Error(Arc<dyn StdError + Send + Sync>);
15
16impl Error {
17    pub fn new<E: StdError + Send + Sync + 'static>(error: E) -> Self {
18        Self(Arc::new(error))
19    }
20
21    pub fn msg(message: impl fmt::Display) -> Self {
22        Self::new(Message(message.to_string()))
23    }
24
25    pub fn downcast_ref<E: StdError + 'static>(&self) -> Option<&E> {
26        self.0.downcast_ref()
27    }
28
29    pub fn is<E: StdError + 'static>(&self) -> bool {
30        self.0.is::<E>()
31    }
32
33    /// `true` for the non-failure outcome of an iteration boundary.
34    pub fn is_interrupted(&self) -> bool {
35        self.is::<Interrupted>()
36    }
37
38    pub fn as_std(&self) -> &(dyn StdError + Send + Sync + 'static) {
39        &*self.0
40    }
41
42    /// Whether two handles refer to the same error value.
43    pub fn ptr_eq(&self, other: &Error) -> bool {
44        Arc::ptr_eq(&self.0, &other.0)
45    }
46
47    /// Converts a caught unwind payload at a plugin callback boundary.
48    pub fn from_panic(payload: Box<dyn std::any::Any + Send>) -> Self {
49        let message = payload
50            .downcast_ref::<&str>()
51            .map(|s| s.to_string())
52            .or_else(|| payload.downcast_ref::<String>().cloned())
53            .unwrap_or_else(|| "unknown panic".into());
54        Self::new(Panicked(message))
55    }
56}
57
58impl<E: StdError + Send + Sync + 'static> From<E> for Error {
59    fn from(error: E) -> Self {
60        Self::new(error)
61    }
62}
63
64impl fmt::Display for Error {
65    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
66        fmt::Display::fmt(&self.0, f)
67    }
68}
69
70impl fmt::Debug for Error {
71    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
72        fmt::Debug::fmt(&self.0, f)
73    }
74}
75
76pub type Result<T, E = Error> = std::result::Result<T, E>;
77
78#[derive(Debug, thiserror::Error)]
79#[error("{0}")]
80struct Message(String);
81
82#[derive(Debug, Clone, thiserror::Error)]
83#[error("panicked: {0}")]
84pub struct Panicked(pub String);
85
86/// Returned by an iteration boundary whose effect (or fiber load) has been
87/// superseded. Propagating it with `?` is not a failure: what was collected
88/// so far is disposed normally.
89#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
90#[error("interrupted at an iteration boundary")]
91pub struct Interrupted;
92
93#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
94pub enum KardiaError {
95    #[error("cannot create effect on inactive context")]
96    InactiveEffect,
97    #[error("service \"{key}\" has been registered at <{by}>")]
98    AlreadyProvided { key: Key, by: String },
99    #[error("cannot set property \"{key}\" without provide")]
100    NotProvided { key: Key },
101    #[error("cannot set property \"{key}\" in multiple fibers")]
102    ForeignBinding { key: Key },
103}
104
105#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
106pub enum AccessError {
107    #[error("cannot get property \"{key}\" without inject")]
108    Undeclared { key: Key },
109    #[error("cannot get required service \"{key}\" in inactive context")]
110    Inactive { key: Key },
111    #[error("service \"{key}\" is not of type {expected}")]
112    TypeMismatch { key: Key, expected: &'static str },
113}
114
115/// Several independent failures, e.g. of the listeners of a parallel event.
116#[derive(Debug, Clone, thiserror::Error)]
117#[error("{message}")]
118pub struct AggregateError {
119    pub message: String,
120    pub errors: Vec<Error>,
121}