iota_types/storage/
error.rs

1// Copyright (c) Mysten Labs, Inc.
2// Modifications Copyright (c) 2024 IOTA Stiftung
3// SPDX-License-Identifier: Apache-2.0
4
5use typed_store_error::TypedStoreError;
6
7pub type Result<T, E = Error> = ::std::result::Result<T, E>;
8
9#[derive(Debug)]
10pub struct Error {
11    inner: Box<Inner>,
12}
13
14type BoxError = Box<dyn std::error::Error + Send + Sync + 'static>;
15
16#[derive(Debug)]
17struct Inner {
18    kind: Kind,
19    source: Option<BoxError>,
20}
21
22#[derive(Copy, Clone, Debug, PartialEq, Eq)]
23pub enum Kind {
24    Serialization,
25    Missing,
26    Custom,
27}
28
29impl Error {
30    fn new<E: Into<BoxError>>(kind: Kind, source: Option<E>) -> Self {
31        Self {
32            inner: Box::new(Inner {
33                kind,
34                source: source.map(Into::into),
35            }),
36        }
37    }
38
39    pub fn serialization<E: Into<BoxError>>(e: E) -> Self {
40        Self::new(Kind::Serialization, Some(e))
41    }
42
43    pub fn missing<E: Into<BoxError>>(e: E) -> Self {
44        Self::new(Kind::Missing, Some(e))
45    }
46
47    pub fn custom<E: Into<BoxError>>(e: E) -> Self {
48        Self::new(Kind::Custom, Some(e))
49    }
50
51    pub fn kind(&self) -> Kind {
52        self.inner.kind
53    }
54}
55
56impl std::error::Error for Error {
57    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
58        self.inner.source.as_ref().map(|e| &**e as _)
59    }
60}
61
62impl std::fmt::Display for Error {
63    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
64        // TODO: change output based on kind?
65        write!(f, "{:?}", self)
66    }
67}
68
69impl From<TypedStoreError> for Error {
70    fn from(e: TypedStoreError) -> Self {
71        Self::custom(e)
72    }
73}