switchgear_pingora/
error.rs

1use std::borrow::Cow;
2use std::error::Error;
3use std::fmt::{Display, Formatter};
4use switchgear_service_api::service::{HasServiceErrorSource, ServiceErrorSource};
5use thiserror::Error;
6
7#[derive(Error, Debug)]
8pub enum PingoraLnErrorSourceKind {
9    #[error("{0}")]
10    Error(String),
11    #[error("no available lightning nodes")]
12    NoAvailableNodes,
13    #[error("{0}")]
14    ServiceError(Box<dyn std::error::Error + Send + Sync + 'static>),
15}
16
17#[derive(Error, Debug)]
18pub struct PingoraLnError {
19    context: Cow<'static, str>,
20    #[source]
21    source: PingoraLnErrorSourceKind,
22    esource: ServiceErrorSource,
23}
24
25impl Display for PingoraLnError {
26    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
27        write!(
28            f,
29            "PingoraLnError: while {}: {}",
30            self.context.as_ref(),
31            self.source
32        )
33    }
34}
35
36impl PingoraLnError {
37    pub fn new<C: Into<Cow<'static, str>>>(
38        source: PingoraLnErrorSourceKind,
39        esource: ServiceErrorSource,
40        context: C,
41    ) -> Self {
42        Self {
43            context: context.into(),
44            source,
45            esource,
46        }
47    }
48
49    pub fn no_available_nodes<C: Into<Cow<'static, str>>>(
50        esource: ServiceErrorSource,
51        context: C,
52    ) -> Self {
53        Self {
54            context: context.into(),
55            source: PingoraLnErrorSourceKind::NoAvailableNodes,
56            esource,
57        }
58    }
59
60    pub fn from_service_error<
61        E: Error + HasServiceErrorSource + Send + Sync + 'static,
62        C: Into<Cow<'static, str>>,
63    >(
64        context: C,
65        source: E,
66    ) -> Self {
67        Self {
68            context: context.into(),
69            esource: source.get_service_error_source(),
70            source: PingoraLnErrorSourceKind::ServiceError(source.into()),
71        }
72    }
73
74    pub fn general_error<C: Into<Cow<'static, str>>>(
75        esource: ServiceErrorSource,
76        context: C,
77        error: String,
78    ) -> Self {
79        Self {
80            context: context.into(),
81            source: PingoraLnErrorSourceKind::Error(error),
82            esource,
83        }
84    }
85
86    /// Get the context message
87    pub fn context(&self) -> &str {
88        self.context.as_ref()
89    }
90
91    /// Get the error source
92    pub fn source(&self) -> &PingoraLnErrorSourceKind {
93        &self.source
94    }
95
96    /// Get the service error source
97    pub fn esource(&self) -> ServiceErrorSource {
98        self.esource
99    }
100}
101
102impl HasServiceErrorSource for PingoraLnError {
103    fn get_service_error_source(&self) -> ServiceErrorSource {
104        self.esource
105    }
106}