Skip to main content

krabka_protocol/
error.rs

1use std::str::Utf8Error;
2
3use thiserror::Error;
4
5/// Errors that can occur during wire-protocol encoding or decoding.
6#[derive(Debug, Error)]
7#[non_exhaustive]
8pub enum ProtocolError {
9    /// Decode reached end of buffer before the expected number of bytes.
10    #[error("unexpected end of buffer: needed {needed} more bytes")]
11    UnexpectedEof { needed: usize },
12
13    /// Decoded a value that the schema says is impossible, such as a negative
14    /// array length.
15    #[error("invalid value: {0}")]
16    InvalidValue(&'static str),
17
18    /// Decoded UTF-8 bytes that are not valid UTF-8.
19    #[error("invalid UTF-8 in string field")]
20    InvalidUtf8(#[source] Utf8Error),
21
22    /// Decoded a varint that exceeds the maximum legal length.
23    #[error("varint exceeds {max} bytes")]
24    VarintTooLong { max: usize },
25
26    /// Encountered an unknown API version for a known API key.
27    #[error("unsupported API version {version} for api key {api_key}")]
28    UnsupportedVersion { api_key: i16, version: i16 },
29
30    /// Schema version requested is not within the message's supported range.
31    #[error("schema mismatch: {0}")]
32    SchemaMismatch(&'static str),
33
34    /// Decoded a known KIP-482 tag at a version that its schema does not
35    /// declare. The text matches the exception that Kafka's generated
36    /// `read` method throws.
37    #[error("Tag {tag} is not valid for version {version}")]
38    TagNotValidForVersion { tag: u32, version: i16 },
39
40    /// An encoder was given a length that its wire-format length prefix
41    /// cannot hold, such as a string longer than `i16::MAX` bytes.
42    #[error("{what} length {len} does not fit its wire-format length prefix")]
43    LengthOverflow { what: &'static str, len: usize },
44}
45
46#[cfg(test)]
47mod tests {
48
49    use super::*;
50
51    #[test]
52    fn display_is_useful() {
53        let e = ProtocolError::UnexpectedEof { needed: 4 };
54        assert2::assert!(e.to_string() == "unexpected end of buffer: needed 4 more bytes");
55    }
56}