1
//! Define an error type for the tor-cell crate.
2
use thiserror::Error;
3
use tor_error::{ErrorKind, HasKind};
4

            
5
/// An error type for the tor-cell crate.
6
///
7
/// This type should probably be split into several.  There's more
8
/// than one kind of error that can occur while doing something with
9
/// tor cells.
10
88
#[derive(Error, Debug, Clone)]
11
#[non_exhaustive]
12
pub enum Error {
13
    /// An error that occurred in the tor_bytes crate while decoding an
14
    /// object.
15
    #[error("Error while parsing {parsed}")]
16
    BytesErr {
17
        /// The error that occurred.
18
        #[source]
19
        err: tor_bytes::Error,
20
        /// The thing that was being parsed.
21
        parsed: &'static str,
22
    },
23
    /// We encountered an error while encoding an outgoing message.
24
    ///
25
    /// This is likely to be a bug in somebody's code: either the code in this
26
    /// crate, or in the calling code that provided an unencodable message.
27
    #[error("Error while encoding message")]
28
    EncodeErr(#[from] tor_bytes::EncodeError),
29
    /// There was a programming error somewhere in the code.
30
    #[error("Internal programming error")]
31
    Internal(tor_error::Bug),
32
    /// Protocol violation at the channel level
33
    #[error("Channel protocol violation: {0}")]
34
    ChanProto(String),
35
    /// Protocol violation at the circuit level
36
    #[error("Circuit protocol violation: {0}")]
37
    CircProto(String),
38
    /// Tried to make or use a stream to an invalid destination address.
39
    #[error("Invalid stream target address")]
40
    BadStreamAddress,
41
    /// Tried to construct a message that Tor can't represent.
42
    #[error("Message can't be represented in a Tor cell: {0}")]
43
    CantEncode(&'static str),
44
}
45

            
46
impl HasKind for Error {
47
    fn kind(&self) -> ErrorKind {
48
        use Error as E;
49
        use ErrorKind as EK;
50
        match self {
51
            E::EncodeErr(..) => EK::BadApiUsage,
52
            E::BytesErr { .. } => EK::TorProtocolViolation,
53
            E::Internal(_) => EK::Internal,
54
            E::ChanProto(_) => EK::TorProtocolViolation,
55
            E::CircProto(_) => EK::TorProtocolViolation,
56
            E::BadStreamAddress => EK::BadApiUsage,
57
            E::CantEncode(_) => EK::Internal,
58
        }
59
    }
60
}