cargo_px_env/
error.rs

1//! Errors that can encountered when loading the environment variables set by `cargo px`.
2
3#[derive(Debug)]
4#[non_exhaustive]
5/// An error that can occur when retrieving the value of an env variable set by `cargo px`.
6pub enum VarError {
7    /// The variable is not set.
8    Missing(MissingVarError),
9    /// The variable contains invalid Unicode data.
10    InvalidUnicode(InvalidUnicodeError),
11}
12
13#[derive(Debug)]
14/// One of the env variables that should be set by `cargo px` is not set.
15pub struct MissingVarError {
16    pub(crate) name: &'static str,
17    pub(crate) source: std::env::VarError,
18}
19
20#[derive(Debug)]
21/// One of the env variables that should be set by `cargo px` contains invalid Unicode data.
22pub struct InvalidUnicodeError {
23    pub(crate) name: &'static str,
24    pub(crate) source: std::env::VarError,
25}
26
27impl std::fmt::Display for VarError {
28    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
29        match self {
30            VarError::Missing(e) => std::fmt::Display::fmt(e, f),
31            VarError::InvalidUnicode(e) => std::fmt::Display::fmt(e, f),
32        }
33    }
34}
35
36impl std::error::Error for VarError {
37    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
38        match self {
39            VarError::Missing(e) => Some(e),
40            VarError::InvalidUnicode(e) => Some(e),
41        }
42    }
43}
44
45impl std::fmt::Display for MissingVarError {
46    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
47        write!(f, "The environment variable `{}` is missing. Are you running the command through `cargo px`?", self.name)
48    }
49}
50
51impl std::fmt::Display for InvalidUnicodeError {
52    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
53        write!(
54            f,
55            "The environment variable `{}` contains invalid Unicode data.",
56            self.name
57        )
58    }
59}
60
61impl std::error::Error for MissingVarError {
62    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
63        Some(&self.source)
64    }
65}
66
67impl std::error::Error for InvalidUnicodeError {
68    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
69        Some(&self.source)
70    }
71}