1use std::error::Error as StdError;
2use std::fmt;
3use std::sync::Arc;
4
5use crate::key::Key;
6
7#[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 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 pub fn ptr_eq(&self, other: &Error) -> bool {
44 Arc::ptr_eq(&self.0, &other.0)
45 }
46
47 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#[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#[derive(Debug, Clone, thiserror::Error)]
117#[error("{message}")]
118pub struct AggregateError {
119 pub message: String,
120 pub errors: Vec<Error>,
121}