Skip to main content

netune_http1/
error.rs

1//! Typed failures. The codec never panics on malformed input: every rejection is
2//! one of these, so a hostile or broken peer cannot take the process down.
3
4use std::fmt;
5
6/// A protocol, limit or transport failure while reading a response.
7#[derive(Debug)]
8pub enum HttpError {
9    /// The peer's bytes are not valid HTTP/1.x.
10    Protocol(&'static str),
11    /// A configured limit was exceeded. The peer is either broken or hostile.
12    LimitExceeded(&'static str),
13    /// The transport failed.
14    Io(std::io::Error),
15}
16
17impl HttpError {
18    /// A stable, greppable classification for retry decisions.
19    pub const fn class(&self) -> &'static str {
20        match self {
21            Self::Protocol(_) => "protocol",
22            Self::LimitExceeded(_) => "limit",
23            Self::Io(_) => "io",
24        }
25    }
26
27    /// Whether a retry could plausibly succeed. Only transport failures are
28    /// retryable; a peer speaking broken HTTP will speak it again.
29    pub const fn is_retryable(&self) -> bool {
30        matches!(self, Self::Io(_))
31    }
32}
33
34impl fmt::Display for HttpError {
35    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
36        match self {
37            Self::Protocol(what) => write!(f, "invalid HTTP response: {what}"),
38            Self::LimitExceeded(what) => write!(f, "HTTP response exceeded {what}"),
39            Self::Io(error) => write!(f, "transport error: {error}"),
40        }
41    }
42}
43
44impl std::error::Error for HttpError {
45    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
46        match self {
47            Self::Io(error) => Some(error),
48            _ => None,
49        }
50    }
51}
52
53impl From<std::io::Error> for HttpError {
54    fn from(error: std::io::Error) -> Self {
55        Self::Io(error)
56    }
57}