Skip to main content

http_query/
error.rs

1//! Error and result types.
2
3use std::fmt;
4
5/// A specialized `Result` for this crate.
6pub type Result<T> = std::result::Result<T, Error>;
7
8/// Errors returned by the `http-query` client and helpers.
9#[derive(Debug)]
10#[non_exhaustive]
11pub enum Error {
12    /// The server returned a non-2xx status code.
13    Status {
14        /// The HTTP status code.
15        status: u16,
16        /// The response body (as text, best-effort).
17        body: String,
18    },
19    /// The response advertised no result resource (no `Content-Location`).
20    NoQueryResult,
21    /// The response advertised no equivalent resource (no `Location`).
22    NoEquivalentResource,
23    /// The redirect limit was exceeded while following a QUERY (RFC 10008 ยง2.5).
24    TooManyRedirects,
25    /// An invalid URL or header value.
26    Invalid(String),
27    /// A transport-level error from the underlying HTTP client.
28    #[cfg(feature = "client")]
29    Transport(reqwest::Error),
30    /// A JSON (de)serialization error.
31    #[cfg(feature = "client")]
32    Json(serde_json::Error),
33}
34
35impl fmt::Display for Error {
36    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
37        match self {
38            Error::Status { status, .. } => write!(f, "server returned status {status}"),
39            Error::NoQueryResult => f.write_str("response has no query result location"),
40            Error::NoEquivalentResource => {
41                f.write_str("response has no equivalent resource location")
42            }
43            Error::TooManyRedirects => f.write_str("too many redirects"),
44            Error::Invalid(msg) => write!(f, "invalid input: {msg}"),
45            #[cfg(feature = "client")]
46            Error::Transport(err) => write!(f, "transport error: {err}"),
47            #[cfg(feature = "client")]
48            Error::Json(err) => write!(f, "json error: {err}"),
49        }
50    }
51}
52
53impl std::error::Error for Error {
54    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
55        match self {
56            #[cfg(feature = "client")]
57            Error::Transport(err) => Some(err),
58            #[cfg(feature = "client")]
59            Error::Json(err) => Some(err),
60            _ => None,
61        }
62    }
63}
64
65#[cfg(feature = "client")]
66impl From<reqwest::Error> for Error {
67    fn from(err: reqwest::Error) -> Self {
68        Error::Transport(err)
69    }
70}
71
72#[cfg(feature = "client")]
73impl From<serde_json::Error> for Error {
74    fn from(err: serde_json::Error) -> Self {
75        Error::Json(err)
76    }
77}