Skip to main content

storage_api/
error.rs

1//! Stable failures; callers never infer behavior from diagnostic text.
2use serde::{Deserialize, Serialize};
3#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
4#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
5pub enum StorageErrorCode {
6    InvalidInput,
7    NotFound,
8    Conflict,
9    VolumeFull,
10    Integrity,
11    Unauthorized,
12    Unavailable,
13    ScopeRemoving,
14    SystemFolderProtected,
15    RepositoryIdentityMismatch,
16    ProtocolMismatch,
17    Internal,
18}
19#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
20#[serde(rename_all = "camelCase")]
21pub enum MutationOutcome {
22    NotApplied,
23    Partial,
24    Unknown,
25}
26#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
27#[serde(rename_all = "camelCase")]
28pub struct StorageError {
29    pub code: StorageErrorCode,
30    pub detail: String,
31    pub outcome: MutationOutcome,
32    #[serde(default, skip_serializing_if = "Option::is_none")]
33    pub deleted_objects: Option<u64>,
34}
35impl StorageError {
36    pub fn new(code: StorageErrorCode, detail: impl Into<String>) -> Self {
37        Self {
38            code,
39            detail: detail.into(),
40            outcome: MutationOutcome::NotApplied,
41            deleted_objects: None,
42        }
43    }
44    pub fn uncertain(mut self) -> Self {
45        self.outcome = MutationOutcome::Unknown;
46        self
47    }
48    pub fn partial(mut self, count: u64) -> Self {
49        self.outcome = MutationOutcome::Partial;
50        self.deleted_objects = Some(count);
51        self
52    }
53    pub fn http_status(&self) -> u16 {
54        use StorageErrorCode::*;
55        match self.code {
56            InvalidInput | Integrity => 400,
57            NotFound => 404,
58            Unauthorized | SystemFolderProtected | ScopeRemoving => 403,
59            Conflict | RepositoryIdentityMismatch => 409,
60            VolumeFull => 507,
61            Unavailable | ProtocolMismatch => 503,
62            Internal => 500,
63        }
64    }
65}
66impl std::fmt::Display for StorageError {
67    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
68        write!(f, "{:?}: {}", self.code, self.detail)
69    }
70}
71impl std::error::Error for StorageError {}