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    /// An invalid URL or header value.
24    Invalid(String),
25    /// A transport-level error from the underlying HTTP client.
26    #[cfg(feature = "client")]
27    Transport(reqwest::Error),
28    /// A JSON (de)serialization error.
29    #[cfg(feature = "client")]
30    Json(serde_json::Error),
31}
32
33impl fmt::Display for Error {
34    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
35        match self {
36            Error::Status { status, .. } => write!(f, "server returned status {status}"),
37            Error::NoQueryResult => f.write_str("response has no query result location"),
38            Error::NoEquivalentResource => {
39                f.write_str("response has no equivalent resource location")
40            }
41            Error::Invalid(msg) => write!(f, "invalid input: {msg}"),
42            #[cfg(feature = "client")]
43            Error::Transport(err) => write!(f, "transport error: {err}"),
44            #[cfg(feature = "client")]
45            Error::Json(err) => write!(f, "json error: {err}"),
46        }
47    }
48}
49
50impl std::error::Error for Error {
51    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
52        match self {
53            #[cfg(feature = "client")]
54            Error::Transport(err) => Some(err),
55            #[cfg(feature = "client")]
56            Error::Json(err) => Some(err),
57            _ => None,
58        }
59    }
60}
61
62#[cfg(feature = "client")]
63impl From<reqwest::Error> for Error {
64    fn from(err: reqwest::Error) -> Self {
65        Error::Transport(err)
66    }
67}
68
69#[cfg(feature = "client")]
70impl From<serde_json::Error> for Error {
71    fn from(err: serde_json::Error) -> Self {
72        Error::Json(err)
73    }
74}