steid

@jamesgill /

steid/src/domain/error.rs
1.4 KBCode·Blame·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}
18
19impl DomainError {
20 pub fn validation(field: impl Into<String>, reason: impl Into<String>) -> Self {
21 Self::Validation {
22 field: field.into(),
23 reason: reason.into(),
24 }
25 }
26}
27
28impl fmt::Display for DomainError {
29 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
30 match self {
31 Self::Validation { field, reason } => write!(f, "invalid {field}: {reason}"),
32 Self::NotFound { entity } => write!(f, "{entity} not found"),
33 Self::AlreadyExists { entity } => write!(f, "{entity} already exists"),
34 Self::InvalidCredentials => f.write_str("invalid credentials"),
35 }
36 }
37}
38
39impl std::error::Error for DomainError {}