Skip to main content

jev/
error.rs

1use std::fmt;
2
3/// Errors are kept as owned data so they stay `Send + Sync` on wasm32, where the
4/// underlying `fetch` errors are not.
5#[derive(Debug, Clone, PartialEq)]
6pub enum Error {
7    /// The request could not be sent or its reply could not be read.
8    Http(String),
9    /// The endpoint answered with a non-success status; `message` is its error message, or the start
10    /// of the body when it has none.
11    Status { status: u16, message: String },
12    /// A request could not be encoded or a reply could not be decoded.
13    Decode(String),
14    /// The same question id was given twice, so one question would have replaced the other.
15    DuplicateQuestion(String),
16    /// A question cannot be answered as asked: too many options, an option twice, no levels.
17    Invalid { id: String, why: String },
18    /// The reply has no answer under this question id.
19    MissingAnswer(String),
20    /// The answer under `id` is of another type than the one asked for.
21    WrongType { id: String, expected: &'static str, found: String },
22    /// The answer under `id` gives no probability for one of its levels or options, which rules
23    /// need: reading it as zero would be a confident no that nothing said.
24    MissingProbability { id: String, label: String },
25    /// The answer under `id` isn't one rules can read: a probability outside 0 to 1, a
26    /// distribution that doesn't add up to 1, or a level or option the question doesn't have.
27    BadAnswer { id: String, why: String },
28}
29
30pub type Result<T> = std::result::Result<T, Error>;
31
32impl fmt::Display for Error {
33    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
34        match self {
35            Error::Http(message) => write!(f, "HTTP error: {message}"),
36            Error::Status { status, message } => write!(f, "decisions endpoint returned HTTP {status}: {message}"),
37            Error::Decode(message) => write!(f, "invalid message: {message}"),
38            Error::DuplicateQuestion(id) => write!(f, "question `{id}` is asked twice"),
39            Error::Invalid { id, why } => write!(f, "question `{id}`: {why}"),
40            Error::MissingAnswer(id) => write!(f, "no answer for question `{id}`"),
41            Error::WrongType { id, expected, found } => write!(f, "question `{id}` is a {found}, not a {expected}"),
42            Error::MissingProbability { id, label } => write!(f, "question `{id}` gives no probability for `{label}`"),
43            Error::BadAnswer { id, why } => write!(f, "the answer to question `{id}` can't be read: {why}"),
44        }
45    }
46}
47
48impl std::error::Error for Error {}