Skip to main content

m10_sdk/
error.rs

1use std::error::Error as StdError;
2#[cfg(feature = "service")]
3use std::io::ErrorKind;
4
5use crate::account::AccountIdError;
6use m10_protos::{prost, sdk::TransactionError};
7use m10_signing::SigningError;
8use tonic::Status;
9
10#[derive(thiserror::Error, Debug)]
11pub enum M10Error {
12    #[error(transparent)]
13    Signing(#[from] SigningError),
14    #[error(transparent)]
15    Status(#[from] Status),
16    #[error(transparent)]
17    Transaction(#[from] TransactionError),
18    #[error(transparent)]
19    InvalidAccountId(#[from] AccountIdError),
20    #[error(transparent)]
21    Transport(#[from] tonic::transport::Error),
22    #[error(transparent)]
23    Request(#[from] reqwest::Error),
24    #[error(transparent)]
25    Encoding(#[from] prost::EncodeError),
26    #[error(transparent)]
27    Decoding(#[from] prost::DecodeError),
28    #[error(transparent)]
29    SysTime(#[from] std::time::SystemTimeError),
30    #[error("Invalid transaction")]
31    InvalidTransaction,
32    #[error("Signer required")]
33    NoSigner,
34    #[error(transparent)]
35    WsError(#[from] tokio_tungstenite::tungstenite::error::Error),
36}
37
38pub type M10Result<T> = Result<T, M10Error>;
39
40fn message_or_summary(summary: &str, detail: &str) -> String {
41    let detail = detail.trim();
42    if detail.is_empty() {
43        summary.to_string()
44    } else {
45        detail.to_string()
46    }
47}
48
49fn status_summary(code: tonic::Code) -> &'static str {
50    match code {
51        tonic::Code::Ok => "ok",
52        tonic::Code::Cancelled => "request cancelled",
53        tonic::Code::Unknown => "unknown error",
54        tonic::Code::InvalidArgument => "bad request",
55        tonic::Code::DeadlineExceeded => "deadline exceeded",
56        tonic::Code::NotFound => "not found",
57        tonic::Code::AlreadyExists => "already exists",
58        tonic::Code::PermissionDenied => "unauthorized",
59        tonic::Code::ResourceExhausted => "resource exhausted",
60        tonic::Code::FailedPrecondition => "failed precondition",
61        tonic::Code::Aborted => "request aborted",
62        tonic::Code::OutOfRange => "value out of range",
63        tonic::Code::Unimplemented => "unimplemented",
64        tonic::Code::Internal => "internal error",
65        tonic::Code::Unavailable => "service unavailable",
66        tonic::Code::DataLoss => "data loss",
67        tonic::Code::Unauthenticated => "unauthorized",
68    }
69}
70
71impl M10Error {
72    pub fn get_message(&self) -> String {
73        match self {
74            M10Error::Status(status) => transport_status_message(status).unwrap_or_else(|| {
75                message_or_summary(status_summary(status.code()), status.message())
76            }),
77            M10Error::Transaction(error) => error.user_message(),
78            _ => self.to_string(),
79        }
80    }
81}
82
83#[cfg(feature = "service")]
84fn transport_status_message(status: &Status) -> Option<String> {
85    let mut source = status.source();
86
87    while let Some(error) = source {
88        if let Some(hyper_error) = error.downcast_ref::<hyper::Error>() {
89            if hyper_error.is_timeout() {
90                return Some("connection to server timed out".to_string());
91            }
92
93            if hyper_error.is_closed() || hyper_error.is_incomplete_message() {
94                return Some("connection to server was interrupted".to_string());
95            }
96        }
97
98        if let Some(io_error) = error.downcast_ref::<std::io::Error>() {
99            if matches!(
100                io_error.kind(),
101                ErrorKind::BrokenPipe
102                    | ErrorKind::ConnectionAborted
103                    | ErrorKind::ConnectionReset
104                    | ErrorKind::NotConnected
105                    | ErrorKind::UnexpectedEof
106            ) {
107                return Some("connection to server was interrupted".to_string());
108            }
109        }
110
111        if let Some(h2_error) = error.downcast_ref::<h2::Error>() {
112            if h2_error.is_io() || h2_error.reason().is_some() {
113                return Some("connection to server was interrupted".to_string());
114            }
115        }
116
117        source = error.source();
118    }
119
120    None
121}
122
123#[cfg(not(feature = "service"))]
124fn transport_status_message(_status: &Status) -> Option<String> {
125    None
126}
127
128#[cfg(test)]
129mod tests {
130    use super::*;
131    use m10_protos::sdk::transaction_error::Code;
132    use std::{fmt, sync::Arc};
133
134    #[derive(Debug)]
135    struct WrappedError<E>(E);
136
137    impl<E> fmt::Display for WrappedError<E>
138    where
139        E: fmt::Display,
140    {
141        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
142            self.0.fmt(f)
143        }
144    }
145
146    impl<E> StdError for WrappedError<E>
147    where
148        E: StdError + Send + Sync + 'static,
149    {
150        fn source(&self) -> Option<&(dyn StdError + 'static)> {
151            Some(&self.0)
152        }
153    }
154
155    #[test]
156    fn blank_transaction_errors_fall_back_to_human_summary() {
157        let err = M10Error::Transaction(TransactionError {
158            code: Code::Unauthorized as i32,
159            message: String::new(),
160        });
161
162        assert_eq!(err.get_message(), "unauthorized");
163    }
164
165    #[test]
166    fn explicit_transaction_messages_are_not_prefixed() {
167        let err = M10Error::Transaction(TransactionError {
168            code: Code::DisplayCodeConflict as i32,
169            message: "currency code already in use".to_string(),
170        });
171
172        assert_eq!(err.get_message(), "currency code already in use");
173    }
174
175    #[test]
176    fn blank_status_errors_fall_back_to_human_summary() {
177        let err = M10Error::Status(Status::permission_denied(""));
178
179        assert_eq!(err.get_message(), "unauthorized");
180    }
181
182    #[test]
183    fn explicit_status_messages_are_not_prefixed() {
184        let err = M10Error::Status(Status::permission_denied(
185            "cannot create a root ledger account",
186        ));
187
188        assert_eq!(err.get_message(), "cannot create a root ledger account");
189    }
190
191    #[cfg(feature = "service")]
192    #[test]
193    fn wrapped_h2_disconnects_are_humanized() {
194        let mut status =
195            Status::internal("h2 protocol error: error reading a body from connection");
196        status.set_source(Arc::new(WrappedError(h2::Error::from(
197            h2::Reason::NO_ERROR,
198        ))));
199
200        let err = M10Error::Status(status);
201
202        assert_eq!(err.get_message(), "connection to server was interrupted");
203    }
204
205    #[cfg(feature = "service")]
206    #[test]
207    fn wrapped_io_disconnects_are_humanized() {
208        let io_error = std::io::Error::new(ErrorKind::ConnectionReset, "connection reset by peer");
209        let mut status = Status::internal("transport failure");
210        status.set_source(Arc::new(WrappedError(io_error)));
211
212        let err = M10Error::Status(status);
213
214        assert_eq!(err.get_message(), "connection to server was interrupted");
215    }
216}