Skip to main content

commonware_sync/
error.rs

1//! Error types for the sync example.
2
3use crate::net::ErrorCode;
4use thiserror::Error;
5
6/// Errors that can occur in the sync example.
7#[derive(Debug, Error)]
8pub enum Error {
9    /// Stream error during communication
10    #[error("stream error")]
11    Network(#[from] commonware_stream::encrypted::Error),
12
13    /// Received unexpected response type for a request
14    #[error("unexpected response type for request {request_id}")]
15    UnexpectedResponse { request_id: u64 },
16
17    /// Server returned an error response
18    #[error("server error (code: {code:?}): {message}")]
19    Server { code: ErrorCode, message: String },
20
21    /// Invalid request parameters
22    #[error("invalid request: {0}")]
23    InvalidRequest(String),
24
25    /// Compact target changed between target discovery and state fetch.
26    #[error("stale compact target: {0}")]
27    StaleTarget(String),
28
29    /// Database operation failed
30    #[error("database operation failed")]
31    Database(#[from] commonware_storage::qmdb::Error<commonware_storage::mmr::Family>),
32
33    /// Request channel to I/O task closed unexpectedly
34    #[error("request channel closed - I/O task may have terminated")]
35    RequestChannelClosed,
36
37    /// Response channel closed before receiving response
38    #[error("response channel closed for request {request_id}")]
39    ResponseChannelClosed { request_id: u64 },
40
41    /// Received a malformed response that could not be decoded.
42    #[error("invalid response from server")]
43    InvalidResponse,
44
45    /// Target update channel error
46    #[error("target update channel error: {reason}")]
47    TargetUpdateChannel { reason: String },
48
49    /// Configuration error
50    #[error("invalid configuration: {0}")]
51    InvalidConfig(String),
52}
53
54impl Error {
55    /// Convert this error to a protocol error code for transmission over the network.
56    pub const fn to_error_code(&self) -> ErrorCode {
57        match self {
58            Self::InvalidRequest(_) => ErrorCode::InvalidRequest,
59            Self::StaleTarget(_) => ErrorCode::StaleTarget,
60            Self::Database(_) => ErrorCode::DatabaseError,
61            Self::Network(_) => ErrorCode::NetworkError,
62            _ => ErrorCode::InternalError,
63        }
64    }
65}