use crate::{InternalError, access::AccessError, dto::prelude::*};
use std::fmt::{self, Display};
#[derive(CandidType, Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct Error {
pub code: ErrorCode,
pub message: String,
}
impl Error {
#[must_use]
pub const fn new(code: ErrorCode, message: String) -> Self {
Self { code, message }
}
pub fn conflict(message: impl Into<String>) -> Self {
Self::new(ErrorCode::Conflict, message.into())
}
pub fn policy(code: ErrorCode, message: impl Into<String>) -> Self {
Self::new(code, message.into())
}
pub fn forbidden(message: impl Into<String>) -> Self {
Self::new(ErrorCode::Forbidden, message.into())
}
pub fn internal(message: impl Into<String>) -> Self {
Self::new(ErrorCode::Internal, message.into())
}
pub fn invalid(message: impl Into<String>) -> Self {
Self::new(ErrorCode::InvalidInput, message.into())
}
pub fn invariant(message: impl Into<String>) -> Self {
Self::new(ErrorCode::InvariantViolation, message.into())
}
pub fn exhausted(message: impl Into<String>) -> Self {
Self::new(ErrorCode::ResourceExhausted, message.into())
}
pub fn not_found(message: impl Into<String>) -> Self {
Self::new(ErrorCode::NotFound, message.into())
}
pub fn unauthorized(message: impl Into<String>) -> Self {
Self::new(ErrorCode::Unauthorized, message.into())
}
pub fn unavailable(message: impl Into<String>) -> Self {
Self::new(ErrorCode::Unavailable, message.into())
}
}
impl Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "[{:?}] {}", self.code, self.message)
}
}
impl From<AccessError> for Error {
fn from(err: AccessError) -> Self {
Self::from(InternalError::from(err))
}
}
#[derive(CandidType, Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[non_exhaustive]
#[remain::sorted]
pub enum ErrorCode {
Conflict,
Forbidden,
Internal,
InvalidInput,
InvariantViolation,
NotFound,
PolicyReplicaRequiresSingletonWithScaling,
PolicyRoleAlreadyRegistered,
PolicyShardRequiresSingletonWithSharding,
PolicySingletonAlreadyRegisteredUnderParent,
PolicyTenantRequiresSingletonParent,
ResourceExhausted,
Unauthorized,
Unavailable,
}