summaryrefslogtreecommitdiffstats
path: root/src/error.rs
blob: b771dedbb0cfbdc8d4277530be02ee6901e5fe5b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
//! Error type.
//!
//! Everything the library can fail with is one [`Error`], so a caller who only
//! cares that *something* went wrong matches one type and is done.
//!
//! Below that, the split is by **the decision the caller has to make**, not by
//! the HTTP status that caused it:
//!
//! - [`Error::InvalidCep`] and [`Error::NotFound`] are problems with the
//!   *request*. Retrying is pointless — the same CEP will fail again.
//! - [`Error::Network`], [`Error::Server`] and [`Error::RateLimited`] are
//!   problems with *transport*. Retrying may help, and the client already
//!   retried on its own before returning any of them.
//!
//! That split is why `NotFound` is not "the HTTP 404 variant": the client also
//! returns `InvalidCep` without making any request at all, when the CEP is
//! malformed before it ever leaves the machine.
//!
//! [`Error::NotFound`] may carry a [`Faixa`] — the municipality the CEP would
//! have belonged to. That is context on the failure and changes nothing about
//! it: the answer is still 404 and the CEP still does not exist.

use std::error::Error as StdError;
use std::fmt;
use std::time::Duration;

use crate::model::Faixa;

/// The result of every fallible operation in this crate.
pub type Result<T> = std::result::Result<T, Error>;

/// Everything that can go wrong when talking to the API.
///
/// Use [`Error::is_retriable`] when the choice is simply "give up or try again
/// later"; match on the variants when the caller needs to tell a bad CEP from a
/// bad network.
#[derive(Debug)]
#[non_exhaustive]
pub enum Error {
    /// The CEP is not 8 digits.
    ///
    /// Usually returned **without** a request ever being made — the client
    /// checks the format before going to the network. It is also what a 400
    /// from the API becomes, in which case the message is the API's own.
    InvalidCep {
        /// Human-readable explanation, including the offending value.
        message: String,
    },

    /// The CEP is well-formed but does not exist in the DNE database.
    NotFound {
        /// The CEP that was looked up, unmasked.
        cep: String,
        /// The municipality this CEP *would* belong to, when the API knows it.
        ///
        /// Still an error, and still a 404 — see [`Faixa`] before showing any
        /// of it to a user. `None` when the CEP falls in a band no municipality
        /// owns, and also whenever the field cannot be read: an unparseable
        /// `faixa` never costs the not-found.
        ///
        /// Boxed to keep [`Error`] small: it travels in the `Err` of every
        /// [`Result`] in this crate, including the ones that never carry a
        /// `faixa`. [`Error::faixa`] hides the box at the call site.
        faixa: Option<Box<Faixa>>,
    },

    /// The API (or the edge in front of it) answered 429 on every attempt.
    RateLimited {
        /// Human-readable explanation.
        message: String,
        /// What the server asked for via `Retry-After`, or `None` if it did not
        /// say. The client already honoured it across the attempts it made; it
        /// is exposed here for callers who want to reschedule the work.
        retry_after: Option<Duration>,
    },

    /// The API answered 5xx on every attempt.
    Server {
        /// Human-readable explanation.
        message: String,
        /// The HTTP status seen on the last attempt.
        status: u16,
    },

    /// The request never completed: DNS, refused connection, timeout, TLS.
    ///
    /// Returned only after every configured attempt has failed.
    Network {
        /// Human-readable explanation.
        message: String,
        /// The underlying transport error, when there is one.
        source: Option<Box<dyn StdError + Send + Sync>>,
    },

    /// A success status came back with a body that cannot be parsed.
    ///
    /// In practice this means something between you and the API is answering
    /// instead of it — a captive Wi-Fi portal, a corporate proxy, an HTML error
    /// page. Useful as a diagnosis: the problem is not in your code.
    InvalidResponse {
        /// Human-readable explanation.
        message: String,
    },
}

impl Error {
    /// Whether trying the same call again later could plausibly succeed.
    ///
    /// `true` for [`Error::RateLimited`], [`Error::Server`] and
    /// [`Error::Network`]; `false` for a bad or unknown CEP, which fails the
    /// same way forever.
    ///
    /// The client has already retried internally by the time any of these are
    /// returned, so "later" means later — not immediately.
    pub fn is_retriable(&self) -> bool {
        matches!(
            self,
            Error::RateLimited { .. } | Error::Server { .. } | Error::Network { .. }
        )
    }

    /// The municipality of a [`Error::NotFound`], when the API named one.
    ///
    /// `None` for every other variant, and for a not-found the API could not
    /// place. It is context for the failure, not a result: the CEP asked for
    /// still does not exist.
    ///
    /// ```no_run
    /// # let cep_from_form = "25845000";
    /// if let Err(err) = cepis::lookup(cep_from_form) {
    ///     match err.faixa() {
    ///         Some(faixa) => println!("no such CEP in {}", faixa.municipality()),
    ///         None => println!("no such CEP"),
    ///     }
    /// }
    /// ```
    pub fn faixa(&self) -> Option<&Faixa> {
        match self {
            Error::NotFound { faixa, .. } => faixa.as_deref(),
            _ => None,
        }
    }

    pub(crate) fn invalid_cep(message: impl Into<String>) -> Self {
        Error::InvalidCep {
            message: message.into(),
        }
    }

    pub(crate) fn invalid_response(message: impl Into<String>) -> Self {
        Error::InvalidResponse {
            message: message.into(),
        }
    }

    pub(crate) fn network(
        message: impl Into<String>,
        source: Option<Box<dyn StdError + Send + Sync>>,
    ) -> Self {
        Error::Network {
            message: message.into(),
            source,
        }
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Error::InvalidCep { message } => f.write_str(message),
            Error::NotFound { cep, faixa: None } => {
                write!(f, "CEP {cep} does not exist in the DNE database")
            }
            Error::NotFound {
                cep,
                faixa: Some(faixa),
            } => write!(
                f,
                "CEP {cep} does not exist in the DNE database (it would be in {})",
                faixa.municipality()
            ),
            Error::RateLimited { message, .. } => f.write_str(message),
            Error::Server { message, .. } => f.write_str(message),
            Error::Network { message, .. } => f.write_str(message),
            Error::InvalidResponse { message } => f.write_str(message),
        }
    }
}

impl StdError for Error {
    fn source(&self) -> Option<&(dyn StdError + 'static)> {
        match self {
            Error::Network { source, .. } => source.as_ref().map(|e| e.as_ref() as &dyn StdError),
            _ => None,
        }
    }
}