Skip to main content

relay_knowledge/env/
error.rs

1//! Environment validation errors.
2
3use std::{error::Error, fmt};
4
5/// Environment parsing error with the exact variable that failed validation.
6#[derive(Debug, Clone, PartialEq, Eq)]
7pub struct EnvError {
8    pub variable: &'static str,
9    pub kind: EnvErrorKind,
10}
11
12impl EnvError {
13    pub(super) fn empty(variable: &'static str) -> Self {
14        Self {
15            variable,
16            kind: EnvErrorKind::EmptyValue,
17        }
18    }
19
20    pub(super) fn invalid_unicode(variable: &'static str) -> Self {
21        Self {
22            variable,
23            kind: EnvErrorKind::InvalidUnicode,
24        }
25    }
26
27    pub(super) fn invalid_integer(variable: &'static str, value: &str) -> Self {
28        Self {
29            variable,
30            kind: EnvErrorKind::InvalidInteger {
31                value: value.to_owned(),
32            },
33        }
34    }
35
36    pub(super) fn zero(variable: &'static str) -> Self {
37        Self {
38            variable,
39            kind: EnvErrorKind::ZeroValue,
40        }
41    }
42
43    pub(super) fn invalid_boolean(variable: &'static str, value: &str) -> Self {
44        Self {
45            variable,
46            kind: EnvErrorKind::InvalidBoolean {
47                value: value.to_owned(),
48            },
49        }
50    }
51}
52
53/// Error category for environment parsing.
54#[derive(Debug, Clone, PartialEq, Eq)]
55pub enum EnvErrorKind {
56    EmptyValue,
57    InvalidUnicode,
58    InvalidInteger { value: String },
59    InvalidBoolean { value: String },
60    ZeroValue,
61}
62
63impl fmt::Display for EnvError {
64    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
65        match &self.kind {
66            EnvErrorKind::EmptyValue => write!(formatter, "{} must not be empty", self.variable),
67            EnvErrorKind::InvalidUnicode => {
68                write!(formatter, "{} must be valid UTF-8", self.variable)
69            }
70            EnvErrorKind::InvalidInteger { value } => {
71                write!(
72                    formatter,
73                    "{} must be a positive integer, got '{value}'",
74                    self.variable
75                )
76            }
77            EnvErrorKind::InvalidBoolean { value } => write!(
78                formatter,
79                "{} must be true or false, got '{value}'",
80                self.variable
81            ),
82            EnvErrorKind::ZeroValue => {
83                write!(formatter, "{} must be greater than zero", self.variable)
84            }
85        }
86    }
87}
88
89impl Error for EnvError {}