#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ErrorKind {
Network,
Timeout,
Unauthorized,
Forbidden,
NotFound,
Server,
Cancelled,
MalformedResponse,
Transport,
SignIn,
PassphraseRequired,
InvalidPassphrase,
Crypto,
}
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
#[error("{message}")]
Network {
message: String,
path: Option<String>,
},
#[error("{message}")]
Timeout {
message: String,
path: Option<String>,
},
#[error("{message}")]
Unauthorized {
message: String,
status: Option<u16>,
path: Option<String>,
},
#[error("{message}")]
Forbidden {
message: String,
path: Option<String>,
},
#[error("{message}")]
NotFound {
message: String,
path: Option<String>,
},
#[error("{message}")]
Server {
message: String,
status: u16,
path: Option<String>,
},
#[error("{message}")]
Cancelled { message: String },
#[error("{message}")]
MalformedResponse {
message: String,
path: Option<String>,
},
#[error("{message}")]
Transport {
message: String,
status: Option<u16>,
path: Option<String>,
},
#[error("{message}")]
SignIn { message: String },
#[error("the library is encrypted: set its passphrase first")]
PassphraseRequired,
#[error("invalid passphrase: it does not decrypt the library")]
InvalidPassphrase,
#[error(transparent)]
Crypto(#[from] redseat_crypto::Error),
}
pub type Result<T, E = Error> = std::result::Result<T, E>;
impl Error {
pub fn kind(&self) -> ErrorKind {
match self {
Error::Network { .. } => ErrorKind::Network,
Error::Timeout { .. } => ErrorKind::Timeout,
Error::Unauthorized { .. } => ErrorKind::Unauthorized,
Error::Forbidden { .. } => ErrorKind::Forbidden,
Error::NotFound { .. } => ErrorKind::NotFound,
Error::Server { .. } => ErrorKind::Server,
Error::Cancelled { .. } => ErrorKind::Cancelled,
Error::MalformedResponse { .. } => ErrorKind::MalformedResponse,
Error::Transport { .. } => ErrorKind::Transport,
Error::SignIn { .. } => ErrorKind::SignIn,
Error::PassphraseRequired => ErrorKind::PassphraseRequired,
Error::InvalidPassphrase => ErrorKind::InvalidPassphrase,
Error::Crypto(_) => ErrorKind::Crypto,
}
}
pub fn status(&self) -> Option<u16> {
match self {
Error::Unauthorized { status, .. } | Error::Transport { status, .. } => *status,
Error::Forbidden { .. } => Some(403),
Error::NotFound { .. } => Some(404),
Error::Server { status, .. } => Some(*status),
_ => None,
}
}
pub fn path(&self) -> Option<&str> {
match self {
Error::Network { path, .. }
| Error::Timeout { path, .. }
| Error::Unauthorized { path, .. }
| Error::Forbidden { path, .. }
| Error::NotFound { path, .. }
| Error::Server { path, .. }
| Error::MalformedResponse { path, .. }
| Error::Transport { path, .. } => path.as_deref(),
_ => None,
}
}
pub(crate) fn transport(message: impl Into<String>) -> Self {
Error::Transport {
message: message.into(),
status: None,
path: None,
}
}
pub(crate) fn malformed(message: impl Into<String>, path: Option<&str>) -> Self {
Error::MalformedResponse {
message: message.into(),
path: path.map(str::to_owned),
}
}
pub(crate) fn sign_in(message: impl Into<String>) -> Self {
Error::SignIn {
message: message.into(),
}
}
pub fn from_status(status: u16, path: Option<&str>, body: &[u8]) -> Self {
let path = path.map(str::to_owned);
let message = body_message(body).unwrap_or_else(|| format!("HTTP {status}"));
match status {
401 => Error::Unauthorized {
message,
status: Some(status),
path,
},
403 => Error::Forbidden { message, path },
404 => Error::NotFound { message, path },
500.. => Error::Server {
message,
status,
path,
},
_ => Error::Transport {
message,
status: Some(status),
path,
},
}
}
}
fn body_message(body: &[u8]) -> Option<String> {
let value: serde_json::Value = serde_json::from_slice(body).ok()?;
["message", "code", "error", "error_description"]
.iter()
.find_map(|field| {
value
.get(field)
.and_then(|v| v.as_str())
.filter(|s| !s.is_empty())
.map(str::to_owned)
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn maps_statuses_like_the_ts_transport() {
assert_eq!(
Error::from_status(401, None, b"").kind(),
ErrorKind::Unauthorized
);
assert_eq!(
Error::from_status(403, None, b"").kind(),
ErrorKind::Forbidden
);
assert_eq!(
Error::from_status(404, None, b"").kind(),
ErrorKind::NotFound
);
assert_eq!(Error::from_status(502, None, b"").kind(), ErrorKind::Server);
assert_eq!(
Error::from_status(400, None, b"").kind(),
ErrorKind::Transport
);
assert_eq!(Error::from_status(400, None, b"").status(), Some(400));
}
#[test]
fn reads_the_message_of_a_json_body() {
let error = Error::from_status(400, Some("/x"), br#"{"code":"INVALID_TOKEN"}"#);
assert_eq!(error.to_string(), "INVALID_TOKEN");
assert_eq!(error.path(), Some("/x"));
assert_eq!(
Error::from_status(400, None, b"<html>").to_string(),
"HTTP 400"
);
}
}