Skip to main content

crabka_protocol/
error.rs

1use thiserror::Error;
2
3/// Errors that can occur during wire-protocol encoding or decoding.
4#[derive(Debug, Error)]
5#[non_exhaustive]
6pub enum ProtocolError {
7    /// Decode reached end of buffer before the expected number of bytes.
8    #[error("unexpected end of buffer: needed {needed} more bytes")]
9    UnexpectedEof { needed: usize },
10
11    /// Decoded a value that the schema says is impossible (e.g. negative array length).
12    #[error("invalid value: {0}")]
13    InvalidValue(&'static str),
14
15    /// Decoded UTF-8 bytes that are not valid UTF-8.
16    #[error("invalid UTF-8 in string field")]
17    InvalidUtf8(#[source] std::str::Utf8Error),
18
19    /// Decoded a varint that exceeds the maximum legal length.
20    #[error("varint exceeds {max} bytes")]
21    VarintTooLong { max: usize },
22
23    /// Encountered an unknown API version for a known API key.
24    #[error("unsupported API version {version} for api key {api_key}")]
25    UnsupportedVersion { api_key: i16, version: i16 },
26
27    /// Schema version requested is not within the message's supported range.
28    #[error("schema mismatch: {0}")]
29    SchemaMismatch(&'static str),
30}
31
32#[cfg(test)]
33mod tests {
34    use super::*;
35
36    #[test]
37    fn display_is_useful() {
38        let e = ProtocolError::UnexpectedEof { needed: 4 };
39        assert_eq!(
40            e.to_string(),
41            "unexpected end of buffer: needed 4 more bytes"
42        );
43    }
44}