Skip to main content

estat_api/
error.rs

1use std::error::Error;
2use std::fmt::{Display, Formatter};
3
4/// Error type returned by all API calls.
5///
6/// e-Stat reports errors in the `RESULT` element of the body, with a status
7/// of `100` or more. [`Api`](Self::Api) holds that status, not the HTTP status.
8///
9/// # Example
10///
11/// ```
12/// use estat_api::EstatError;
13///
14/// let error = EstatError::Api { status: 100, message: "認証に失敗しました。".into() };
15/// assert!(error.is_unauthorized());
16/// assert_eq!(error.status(), Some(100));
17/// ```
18#[derive(Debug)]
19#[non_exhaustive]
20pub enum EstatError {
21    /// Failed to connect, send the request, or read the response body.
22    ///
23    /// The request URL is removed from the error because it contains the application ID.
24    Connection(reqwest::Error),
25    /// The response body is not the expected JSON.
26    JsonParse(serde_json::Error),
27    /// e-Stat returned an error in `RESULT`.
28    ///
29    /// `100` invalid application ID, `101` to `105` invalid parameters,
30    /// `200` to `299` server errors, `300` no table or dataset with that ID,
31    /// `301` and `302` refused dataset changes, `400` and `401` failed bulk requests.
32    Api {
33        /// `RESULT.STATUS`.
34        status: u16,
35        /// `RESULT.ERROR_MSG`, in Japanese unless English was requested.
36        message: String,
37    },
38    /// The server answered with an HTTP error status and a body that is not
39    /// an e-Stat response, such as a maintenance page. Holds the HTTP status and the body.
40    HttpStatus(u16, String),
41    /// The body is JSON but not shaped like an e-Stat response, or paging did
42    /// not move forward.
43    UnexpectedResponse(String),
44    /// The request was rejected before sending.
45    InvalidArgument(String),
46}
47
48impl EstatError {
49    /// Status of [`Api`](Self::Api) (`RESULT.STATUS`) or
50    /// [`HttpStatus`](Self::HttpStatus) (HTTP status), `None` otherwise.
51    pub fn status(&self) -> Option<u16> {
52        match self {
53            EstatError::Api { status, .. } | EstatError::HttpStatus(status, _) => Some(*status),
54            _ => None,
55        }
56    }
57
58    /// `true` for status `100`: the application ID is wrong.
59    pub fn is_unauthorized(&self) -> bool {
60        self.api_status() == Some(100)
61    }
62
63    /// `true` for status `101` to `105`: a parameter is missing or invalid.
64    pub fn is_invalid_parameter(&self) -> bool {
65        self.api_status().is_some_and(|s| (101..=105).contains(&s))
66    }
67
68    /// `true` for status `300`: no table or dataset with the given ID.
69    pub fn is_not_found(&self) -> bool {
70        self.api_status() == Some(300)
71    }
72
73    /// `true` for status `200` to `299`: a temporary error on the e-Stat side.
74    /// The manual asks to wait before trying again.
75    pub fn is_server_error(&self) -> bool {
76        self.api_status().is_some_and(|s| (200..300).contains(&s))
77    }
78
79    /// `true` when the request timed out.
80    pub fn is_timeout(&self) -> bool {
81        matches!(self, EstatError::Connection(e) if e.is_timeout())
82    }
83
84    fn api_status(&self) -> Option<u16> {
85        match self {
86            EstatError::Api { status, .. } => Some(*status),
87            _ => None,
88        }
89    }
90
91    pub(crate) fn connection(error: reqwest::Error) -> Self {
92        EstatError::Connection(error.without_url())
93    }
94}
95
96impl Display for EstatError {
97    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
98        match self {
99            EstatError::Connection(e) if e.is_timeout() => write!(f, "connection error: timed out"),
100            EstatError::Connection(e) => write!(f, "connection error: {e}"),
101            EstatError::JsonParse(e) => write!(f, "json parse error: {e}"),
102            EstatError::Api { status, message } => write!(f, "e-stat error {status}: {message}"),
103            EstatError::HttpStatus(status, body) => write!(f, "http status {status}: {body}"),
104            EstatError::UnexpectedResponse(e) => write!(f, "unexpected response: {e}"),
105            EstatError::InvalidArgument(e) => write!(f, "invalid argument: {e}"),
106        }
107    }
108}
109
110impl Error for EstatError {
111    fn source(&self) -> Option<&(dyn Error + 'static)> {
112        match self {
113            EstatError::Connection(e) => Some(e),
114            EstatError::JsonParse(e) => Some(e),
115            _ => None,
116        }
117    }
118}
119
120#[cfg(test)]
121mod tests {
122    use super::*;
123
124    fn api(status: u16) -> EstatError {
125        EstatError::Api {
126            status,
127            message: "message".into(),
128        }
129    }
130
131    #[test]
132    fn classifies_api_status() {
133        assert!(api(100).is_unauthorized());
134        assert!(api(101).is_invalid_parameter());
135        assert!(api(105).is_invalid_parameter());
136        assert!(!api(106).is_invalid_parameter());
137        assert!(api(200).is_server_error());
138        assert!(api(299).is_server_error());
139        assert!(!api(300).is_server_error());
140        assert!(api(300).is_not_found());
141        assert_eq!(api(102).to_string(), "e-stat error 102: message");
142
143        // HTTP statuses are not e-Stat statuses
144        let error = EstatError::HttpStatus(300, "body".into());
145        assert_eq!(error.status(), Some(300));
146        assert!(!error.is_not_found());
147        assert!(!error.is_invalid_parameter());
148        assert!(!error.is_server_error());
149    }
150
151    #[test]
152    fn connection_errors() {
153        // A builder error is the only reqwest::Error that can be made without I/O
154        let request = reqwest::Client::new().get("not a url").build();
155        let error = EstatError::connection(request.unwrap_err());
156        assert!(!error.is_timeout());
157        assert!(error.to_string().starts_with("connection error: "));
158        assert!(error.source().is_some());
159        assert_eq!(error.status(), None);
160    }
161
162    #[test]
163    fn display_and_source() {
164        let json = serde_json::from_str::<serde_json::Value>("{").unwrap_err();
165        let error = EstatError::JsonParse(json);
166        assert!(error.to_string().starts_with("json parse error: "));
167        assert!(error.source().is_some());
168        assert_eq!(error.status(), None);
169
170        let error = EstatError::HttpStatus(503, "maintenance".into());
171        assert_eq!(error.to_string(), "http status 503: maintenance");
172        assert!(error.source().is_none());
173        assert!(!error.is_timeout());
174        assert!(!error.is_unauthorized());
175
176        let error = EstatError::UnexpectedResponse("no RESULT".into());
177        assert_eq!(error.to_string(), "unexpected response: no RESULT");
178        let error = EstatError::InvalidArgument("bad".into());
179        assert_eq!(error.to_string(), "invalid argument: bad");
180    }
181}