Skip to main content

tilo_net/
error.rs

1//! The one error type of every network operation.
2
3use crate::Unsupported;
4
5#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
6#[non_exhaustive]
7pub enum NetError {
8    #[error(transparent)]
9    Unsupported(#[from] Unsupported),
10    #[error("invalid URL: {0}")]
11    InvalidUrl(String),
12    #[error("invalid request: {0}")]
13    InvalidRequest(String),
14    #[error("timed out")]
15    Timeout,
16    /// The server was not reached, or the connection failed. A page reports a
17    /// refused cross-origin response the same way.
18    #[error("{}", connect_message(message, *cross_origin))]
19    Connect { message: String, cross_origin: bool },
20    #[error("the fetch proxy refused this destination: {0}")]
21    Blocked(String),
22    #[error("HTTP {0}")]
23    Status(http::StatusCode),
24    #[error("response body: {0}")]
25    Body(String),
26    #[error("the response is larger than {limit} bytes")]
27    TooLarge { limit: usize },
28    #[error("the server redirected and the request does not follow redirects")]
29    Redirect,
30    #[error("the connection is closed")]
31    Closed,
32    #[error("the connection closed ({code}): {reason}")]
33    ClosedWith { code: u32, reason: String },
34    #[error("{0}")]
35    Protocol(String),
36}
37
38fn connect_message(message: &str, cross_origin: bool) -> String {
39    if cross_origin {
40        format!(
41            "{message} (the site may not allow this page to read its responses; an offline network fails the same way)"
42        )
43    } else {
44        message.to_owned()
45    }
46}
47
48impl NetError {
49    pub(crate) fn connect(message: impl Into<String>) -> Self {
50        Self::Connect {
51            message: message.into(),
52            cross_origin: false,
53        }
54    }
55
56    #[must_use]
57    pub fn is_timeout(&self) -> bool {
58        matches!(self, Self::Timeout)
59    }
60
61    #[must_use]
62    pub fn is_connect(&self) -> bool {
63        matches!(self, Self::Connect { .. })
64    }
65
66    #[must_use]
67    pub fn may_be_cors(&self) -> bool {
68        matches!(
69            self,
70            Self::Connect {
71                cross_origin: true,
72                ..
73            }
74        )
75    }
76
77    #[must_use]
78    pub fn status(&self) -> Option<http::StatusCode> {
79        match self {
80            Self::Status(status) => Some(*status),
81            _ => None,
82        }
83    }
84}
85
86#[cfg(feature = "webtransport")]
87impl web_transport_trait::Error for NetError {
88    fn session_error(&self) -> Option<(u32, String)> {
89        match self {
90            Self::ClosedWith { code, reason } => Some((*code, reason.clone())),
91            _ => None,
92        }
93    }
94}