Skip to main content

hal_sdk/
error.rs

1use std::error::Error;
2use std::fmt;
3
4/// Errors that can occur while talking to the HAL API.
5#[derive(Debug)]
6pub enum HalError {
7    /// The HTTP request itself failed (network error, timeout, TLS, …).
8    Request(reqwest::Error),
9    /// The response body could not be decoded into the expected structure.
10    Json(serde_json::Error),
11    /// The API returned an unexpected HTTP status code.
12    Api {
13        /// The HTTP status code returned by HAL.
14        status: u16,
15        /// The (possibly truncated) response body, useful for debugging.
16        body: String,
17    },
18}
19
20impl fmt::Display for HalError {
21    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
22        match self {
23            HalError::Request(err) => write!(f, "HTTP request error: {err}"),
24            HalError::Json(err) => write!(f, "JSON decoding error: {err}"),
25            HalError::Api { status, body } => {
26                write!(f, "HAL API returned status {status}: {body}")
27            }
28        }
29    }
30}
31
32impl Error for HalError {
33    fn source(&self) -> Option<&(dyn Error + 'static)> {
34        match self {
35            HalError::Request(err) => Some(err),
36            HalError::Json(err) => Some(err),
37            HalError::Api { .. } => None,
38        }
39    }
40}
41
42impl From<reqwest::Error> for HalError {
43    fn from(err: reqwest::Error) -> Self {
44        HalError::Request(err)
45    }
46}
47
48impl From<serde_json::Error> for HalError {
49    fn from(err: serde_json::Error) -> Self {
50        HalError::Json(err)
51    }
52}