use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum ErrorCode {
InvalidInput,
Unauthorized,
Forbidden,
ResourceNotFound,
Conflict,
RateLimited,
Internal,
Unavailable,
Timeout,
}
impl ErrorCode {
#[cfg(feature = "http")]
pub fn to_http_status(&self) -> http::StatusCode {
use http::StatusCode;
match self {
Self::InvalidInput => StatusCode::BAD_REQUEST,
Self::Unauthorized => StatusCode::UNAUTHORIZED,
Self::Forbidden => StatusCode::FORBIDDEN,
Self::ResourceNotFound => StatusCode::NOT_FOUND,
Self::Conflict => StatusCode::CONFLICT,
Self::RateLimited => StatusCode::TOO_MANY_REQUESTS,
Self::Internal => StatusCode::INTERNAL_SERVER_ERROR,
Self::Unavailable => StatusCode::SERVICE_UNAVAILABLE,
Self::Timeout => StatusCode::GATEWAY_TIMEOUT,
}
}
#[cfg(feature = "grpc")]
pub fn to_grpc_code(&self) -> tonic::Code {
use tonic::Code;
match self {
Self::InvalidInput => Code::InvalidArgument,
Self::Unauthorized => Code::Unauthenticated,
Self::Forbidden => Code::PermissionDenied,
Self::ResourceNotFound => Code::NotFound,
Self::Conflict => Code::AlreadyExists,
Self::RateLimited => Code::ResourceExhausted,
Self::Internal => Code::Internal,
Self::Unavailable => Code::Unavailable,
Self::Timeout => Code::DeadlineExceeded,
}
}
}
impl std::fmt::Display for ErrorCode {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::InvalidInput => write!(f, "InvalidInput"),
Self::Unauthorized => write!(f, "Unauthorized"),
Self::Forbidden => write!(f, "Forbidden"),
Self::ResourceNotFound => write!(f, "ResourceNotFound"),
Self::Conflict => write!(f, "Conflict"),
Self::RateLimited => write!(f, "RateLimited"),
Self::Internal => write!(f, "Internal"),
Self::Unavailable => write!(f, "Unavailable"),
Self::Timeout => write!(f, "Timeout"),
}
}
}