Skip to main content

powhttp_sdk/
error.rs

1/// Error type returned by extension handlers and SDK operations.
2#[derive(Debug)]
3pub enum Error {
4    Handler(Box<dyn std::error::Error + Send + Sync>),
5    Request(tokio_jrpc::ClientError),
6    Runtime(tokio_jrpc::RuntimeError),
7}
8
9impl Error {
10    /// Wraps any error type into [`Error::Handler`].
11    pub fn new<E>(error: E) -> Self
12    where E: Into<Box<dyn std::error::Error + Send + Sync>> {
13        Self::Handler(error.into())
14    }
15
16    pub(crate) fn into_jrpc(self) -> tokio_jrpc::Error {
17        let message = match self {
18            Self::Handler(msg) => msg.to_string(),
19            Self::Request(err) => err.to_string(),
20            Self::Runtime(err) => err.to_string(),
21        };
22        tokio_jrpc::Error {
23            code: tokio_jrpc::ErrorCode::InternalError,
24            message,
25            data: None,
26        }
27    }
28}
29
30impl std::fmt::Display for Error {
31    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
32        match self {
33            Self::Handler(e) => e.fmt(f),
34            Self::Request(e) => e.fmt(f),
35            Self::Runtime(e) => e.fmt(f),
36        }
37    }
38}
39
40impl std::error::Error for Error {
41    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
42        match self {
43            Self::Handler(e) => Some(e.as_ref()),
44            Self::Request(e) => Some(e),
45            Self::Runtime(e) => Some(e),
46        }
47    }
48}
49
50impl From<tokio_jrpc::ClientError> for Error {
51    fn from(error: tokio_jrpc::ClientError) -> Self {
52        Self::Request(error)
53    }
54}
55
56impl From<tokio_jrpc::RuntimeError> for Error {
57    fn from(error: tokio_jrpc::RuntimeError) -> Self {
58        Self::Runtime(error)
59    }
60}