Skip to main content

dig_dht/
error.rs

1//! [`DhtError`] — the crate's error type.
2
3use thiserror::Error;
4
5/// An error from a DHT operation.
6#[derive(Debug, Error)]
7pub enum DhtError {
8    /// A transport-level failure talking to a peer (connect failed, stream error, timeout). Carries
9    /// the underlying reason as text — the DHT treats a transport failure to one peer as that peer
10    /// being unreachable and continues the lookup with others.
11    #[error("transport error: {0}")]
12    Transport(String),
13
14    /// A peer's response could not be parsed / did not match the expected shape for the request.
15    #[error("malformed response: {0}")]
16    MalformedResponse(String),
17
18    /// A hex `peer_id` / content key / root supplied to the API was not valid 64-char hex.
19    #[error("invalid hex identifier: {0}")]
20    InvalidHex(String),
21
22    /// The lookup could not proceed because the routing table + bootstrap set were empty — there is
23    /// no one to ask. Bootstrap the node with at least one reachable peer first.
24    #[error("no peers to query (routing table + bootstrap set are empty)")]
25    NoPeers,
26
27    /// The RPC timed out waiting for a peer response.
28    #[error("rpc timed out")]
29    Timeout,
30}
31
32impl DhtError {
33    /// Convenience: build a [`DhtError::Transport`] from anything displayable.
34    pub fn transport(e: impl std::fmt::Display) -> Self {
35        DhtError::Transport(e.to_string())
36    }
37}
38
39#[cfg(test)]
40mod tests {
41    use super::*;
42
43    #[test]
44    fn transport_helper_formats() {
45        let e = DhtError::transport("connection refused");
46        assert!(e.to_string().contains("connection refused"));
47        assert!(matches!(e, DhtError::Transport(_)));
48    }
49
50    #[test]
51    fn error_messages_are_descriptive() {
52        assert!(DhtError::NoPeers.to_string().contains("no peers"));
53        assert!(DhtError::Timeout.to_string().contains("timed out"));
54        assert!(DhtError::MalformedResponse("x".into())
55            .to_string()
56            .contains("malformed"));
57    }
58}