use std::fmt;
use std::str::FromStr;
use std::sync::Arc;
use std::time::Duration;
pub type Result<T> = std::result::Result<T, Error>;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[non_exhaustive]
pub enum ErrorCode {
Config,
Authentication,
PermissionDenied,
NotFound,
Conflict,
RateLimited,
Validation,
Unavailable,
Timeout,
Unsupported,
Cancelled,
}
impl ErrorCode {
pub const ALL: [ErrorCode; 11] = [
ErrorCode::Config,
ErrorCode::Authentication,
ErrorCode::PermissionDenied,
ErrorCode::NotFound,
ErrorCode::Conflict,
ErrorCode::RateLimited,
ErrorCode::Validation,
ErrorCode::Unavailable,
ErrorCode::Timeout,
ErrorCode::Unsupported,
ErrorCode::Cancelled,
];
pub fn as_str(self) -> &'static str {
match self {
ErrorCode::Config => "CONFIG",
ErrorCode::Authentication => "AUTHENTICATION",
ErrorCode::PermissionDenied => "PERMISSION_DENIED",
ErrorCode::NotFound => "NOT_FOUND",
ErrorCode::Conflict => "CONFLICT",
ErrorCode::RateLimited => "RATE_LIMITED",
ErrorCode::Validation => "VALIDATION",
ErrorCode::Unavailable => "UNAVAILABLE",
ErrorCode::Timeout => "TIMEOUT",
ErrorCode::Unsupported => "UNSUPPORTED",
ErrorCode::Cancelled => "CANCELLED",
}
}
pub fn default_retryable(self) -> bool {
matches!(
self,
ErrorCode::RateLimited | ErrorCode::Unavailable | ErrorCode::Timeout
)
}
pub fn reason(self) -> &'static str {
match self {
ErrorCode::Config => "invalid configuration",
ErrorCode::Authentication => "authentication failed",
ErrorCode::PermissionDenied => "permission denied",
ErrorCode::NotFound => "not found",
ErrorCode::Conflict => "conflict",
ErrorCode::RateLimited => "rate limited",
ErrorCode::Validation => "invalid request",
ErrorCode::Unavailable => "service unavailable",
ErrorCode::Timeout => "timed out",
ErrorCode::Unsupported => "not supported",
ErrorCode::Cancelled => "cancelled",
}
}
pub fn from_http_status(status: u16) -> Option<ErrorCode> {
Some(match status {
401 => ErrorCode::Authentication,
403 => ErrorCode::PermissionDenied,
404 => ErrorCode::NotFound,
409 | 412 => ErrorCode::Conflict,
429 => ErrorCode::RateLimited,
408 | 504 => ErrorCode::Timeout,
501 => ErrorCode::Unsupported,
400..=499 => ErrorCode::Validation,
500..=599 => ErrorCode::Unavailable,
_ => return None,
})
}
}
impl fmt::Display for ErrorCode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
impl FromStr for ErrorCode {
type Err = Error;
fn from_str(s: &str) -> Result<Self> {
ErrorCode::ALL
.into_iter()
.find(|c| c.as_str() == s)
.ok_or_else(|| Error::validation(format!("unknown error code {s:?}")))
}
}
#[derive(Clone)]
pub struct ErrorContext {
message: String,
http_status: Option<u16>,
request_id: Option<String>,
retryable: bool,
retry_after: Option<Duration>,
source: Option<Arc<dyn std::error::Error + Send + Sync + 'static>>,
}
impl fmt::Debug for ErrorContext {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ErrorContext")
.field("message", &self.message)
.field("http_status", &self.http_status)
.field("request_id", &self.request_id)
.field("retryable", &self.retryable)
.field("retry_after", &self.retry_after)
.field("source", &self.source.as_ref().map(|s| s.to_string()))
.finish()
}
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum Error {
Config(Box<ErrorContext>),
Authentication(Box<ErrorContext>),
PermissionDenied(Box<ErrorContext>),
NotFound(Box<ErrorContext>),
Conflict(Box<ErrorContext>),
RateLimited(Box<ErrorContext>),
Validation(Box<ErrorContext>),
Unavailable(Box<ErrorContext>),
Timeout(Box<ErrorContext>),
Unsupported(Box<ErrorContext>),
Cancelled(Box<ErrorContext>),
}
impl Error {
pub fn new(code: ErrorCode, message: impl Into<String>) -> Self {
let ctx = Box::new(ErrorContext {
message: message.into(),
http_status: None,
request_id: None,
retryable: code.default_retryable(),
retry_after: None,
source: None,
});
match code {
ErrorCode::Config => Error::Config(ctx),
ErrorCode::Authentication => Error::Authentication(ctx),
ErrorCode::PermissionDenied => Error::PermissionDenied(ctx),
ErrorCode::NotFound => Error::NotFound(ctx),
ErrorCode::Conflict => Error::Conflict(ctx),
ErrorCode::RateLimited => Error::RateLimited(ctx),
ErrorCode::Validation => Error::Validation(ctx),
ErrorCode::Unavailable => Error::Unavailable(ctx),
ErrorCode::Timeout => Error::Timeout(ctx),
ErrorCode::Unsupported => Error::Unsupported(ctx),
ErrorCode::Cancelled => Error::Cancelled(ctx),
}
}
pub fn from_status(status: u16, message: impl Into<String>) -> Self {
let code = ErrorCode::from_http_status(status).unwrap_or(ErrorCode::Unavailable);
Error::new(code, message).with_status(status)
}
pub fn config(message: impl Into<String>) -> Self {
Error::new(ErrorCode::Config, message)
}
pub fn validation(message: impl Into<String>) -> Self {
Error::new(ErrorCode::Validation, message)
}
pub fn not_found(message: impl Into<String>) -> Self {
Error::new(ErrorCode::NotFound, message)
}
pub fn conflict(message: impl Into<String>) -> Self {
Error::new(ErrorCode::Conflict, message)
}
pub fn timeout(message: impl Into<String>) -> Self {
Error::new(ErrorCode::Timeout, message)
}
pub fn unavailable(message: impl Into<String>) -> Self {
Error::new(ErrorCode::Unavailable, message)
}
pub fn unsupported(message: impl Into<String>) -> Self {
Error::new(ErrorCode::Unsupported, message)
}
pub fn cancelled(message: impl Into<String>) -> Self {
Error::new(ErrorCode::Cancelled, message)
}
fn ctx(&self) -> &ErrorContext {
match self {
Error::Config(c)
| Error::Authentication(c)
| Error::PermissionDenied(c)
| Error::NotFound(c)
| Error::Conflict(c)
| Error::RateLimited(c)
| Error::Validation(c)
| Error::Unavailable(c)
| Error::Timeout(c)
| Error::Unsupported(c)
| Error::Cancelled(c) => c,
}
}
fn ctx_mut(&mut self) -> &mut ErrorContext {
match self {
Error::Config(c)
| Error::Authentication(c)
| Error::PermissionDenied(c)
| Error::NotFound(c)
| Error::Conflict(c)
| Error::RateLimited(c)
| Error::Validation(c)
| Error::Unavailable(c)
| Error::Timeout(c)
| Error::Unsupported(c)
| Error::Cancelled(c) => c,
}
}
pub fn with_status(mut self, status: u16) -> Self {
self.ctx_mut().http_status = Some(status);
self
}
pub fn with_request_id(mut self, request_id: impl Into<String>) -> Self {
self.ctx_mut().request_id = Some(request_id.into());
self
}
pub fn with_retryable(mut self, retryable: bool) -> Self {
self.ctx_mut().retryable = retryable;
self
}
pub fn with_retry_after(mut self, retry_after: Duration) -> Self {
self.ctx_mut().retry_after = Some(retry_after);
self
}
pub fn with_source(mut self, source: impl std::error::Error + Send + Sync + 'static) -> Self {
self.ctx_mut().source = Some(Arc::new(source));
self
}
pub fn with_message(mut self, message: impl Into<String>) -> Self {
self.ctx_mut().message = message.into();
self
}
pub fn code(&self) -> ErrorCode {
match self {
Error::Config(_) => ErrorCode::Config,
Error::Authentication(_) => ErrorCode::Authentication,
Error::PermissionDenied(_) => ErrorCode::PermissionDenied,
Error::NotFound(_) => ErrorCode::NotFound,
Error::Conflict(_) => ErrorCode::Conflict,
Error::RateLimited(_) => ErrorCode::RateLimited,
Error::Validation(_) => ErrorCode::Validation,
Error::Unavailable(_) => ErrorCode::Unavailable,
Error::Timeout(_) => ErrorCode::Timeout,
Error::Unsupported(_) => ErrorCode::Unsupported,
Error::Cancelled(_) => ErrorCode::Cancelled,
}
}
pub fn message(&self) -> &str {
&self.ctx().message
}
pub fn http_status(&self) -> Option<u16> {
self.ctx().http_status
}
pub fn request_id(&self) -> Option<&str> {
self.ctx().request_id.as_deref()
}
pub fn is_retryable(&self) -> bool {
self.ctx().retryable
}
pub fn retry_after(&self) -> Option<Duration> {
self.ctx().retry_after
}
pub fn is(&self, code: ErrorCode) -> bool {
self.code() == code
}
pub fn cause(&self) -> Option<&(dyn std::error::Error + Send + Sync + 'static)> {
self.ctx().source.as_deref()
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.ctx().message)
}
}
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
self.ctx()
.source
.as_deref()
.map(|s| s as &(dyn std::error::Error + 'static))
}
}
impl From<serde_json::Error> for Error {
fn from(err: serde_json::Error) -> Self {
Error::validation(format!("invalid JSON: {}", err.classify_name())).with_source(err)
}
}
trait ClassifyName {
fn classify_name(&self) -> &'static str;
}
impl ClassifyName for serde_json::Error {
fn classify_name(&self) -> &'static str {
match self.classify() {
serde_json::error::Category::Io => "I/O error",
serde_json::error::Category::Syntax => "syntax error",
serde_json::error::Category::Data => "unexpected data",
serde_json::error::Category::Eof => "unexpected end of input",
}
}
}