typed_container/
errors.rs1use std::{
2 any::type_name,
3 fmt::{Debug, Display},
4 marker::PhantomData,
5 sync::PoisonError,
6};
7
8use derivative::Derivative;
9
10#[derive(Debug)]
11pub enum ErrorKind {
12 LockPoisoned,
13 Duplicated,
14 NotFound,
15 FailDowncast,
16}
17
18impl Display for ErrorKind {
19 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
20 match self {
21 Self::Duplicated => {
22 write!(f, "Item duplicated")
23 }
24 Self::LockPoisoned => write!(f, "Lock poisoned"),
25 Self::NotFound => write!(f, "Service not found"),
26 Self::FailDowncast => write!(f, "Failed to downcast"),
27 }
28 }
29}
30
31#[derive(Derivative)]
32#[derivative(Debug)]
33pub struct Error<T> {
34 pub kind: ErrorKind,
35 #[derivative(Debug = "ignore")]
36 _marker: PhantomData<T>,
37}
38
39impl<T> Display for Error<T> {
40 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
41 write!(f, "{}: {}", self.kind, type_name::<T>())
42 }
43}
44
45impl<T> std::error::Error for Error<T> {}
46
47impl<T, E> From<PoisonError<E>> for Error<T> {
48 fn from(_: PoisonError<E>) -> Self {
49 Self {
50 kind: ErrorKind::LockPoisoned,
51 _marker: PhantomData,
52 }
53 }
54}
55
56impl<T> From<ErrorKind> for Error<T> {
57 fn from(value: ErrorKind) -> Self {
58 Self {
59 kind: value,
60 _marker: PhantomData,
61 }
62 }
63}