steid

@jamesgill /

steid/src/domain/error.rs
Rust2.9 KBCode·Blame·History·Raw
1use std::fmt;
2
3/// Every way a domain rule can be violated.
4///
5/// Deliberately coarse: a variant earns its place when a caller needs to react to it
6/// differently, not merely to describe a failure more precisely.
7#[derive(Debug, Clone, PartialEq, Eq)]
8pub enum DomainError {
9 /// A value failed validation. Carries the field and the reason.
10 Validation { field: String, reason: String },
11 /// The requested entity does not exist.
12 NotFound { entity: &'static str },
13 /// The entity already exists and the operation requires it not to.
14 AlreadyExists { entity: &'static str },
15 /// Credentials did not match. Deliberately says nothing about which part failed.
16 InvalidCredentials,
17 /// The actor is known but not permitted to do this.
18 ///
19 /// Distinct from [`NotFound`](Self::NotFound): used where the resource is public
20 /// anyway, so pretending it does not exist would be theatre rather than privacy.
21 Forbidden,
22 /// The repository is archived, so it accepts no writes.
23 ///
24 /// Distinct from [`Forbidden`](Self::Forbidden) because it is not about who is
25 /// asking — the owner is refused too — and because it is the one refusal the person
26 /// hitting it can lift themselves. That difference is what earns it a variant: a
27 /// push told "not permitted" would send its owner looking for a permissions problem
28 /// that is not there.
29 Archived,
30 /// The entity exists and the actor may act on it, but its current state does not
31 /// permit this operation.
32 ///
33 /// Distinct from [`Forbidden`](Self::Forbidden), which is about who is asking and
34 /// never becomes true by waiting. This one is about *when*: pushing to a repository
35 /// that is still being imported is refused now and allowed in a minute, and telling
36 /// someone they lack permission would send them to look in the wrong place.
37 Unavailable {
38 entity: &'static str,
39 reason: String,
40 },
41}
42
43impl DomainError {
44 pub fn validation(field: impl Into<String>, reason: impl Into<String>) -> Self {
45 Self::Validation {
46 field: field.into(),
47 reason: reason.into(),
48 }
49 }
50}
51
52impl fmt::Display for DomainError {
53 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
54 match self {
55 Self::Validation { field, reason } => write!(f, "invalid {field}: {reason}"),
56 Self::NotFound { entity } => write!(f, "{entity} not found"),
57 Self::AlreadyExists { entity } => write!(f, "{entity} already exists"),
58 Self::InvalidCredentials => f.write_str("invalid credentials"),
59 Self::Forbidden => f.write_str("not permitted"),
60 Self::Archived => f.write_str("this repository is archived and is read-only"),
61 Self::Unavailable { entity, reason } => write!(f, "{entity} is unavailable: {reason}"),
62 }
63 }
64}
65
66impl std::error::Error for DomainError {}