Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Proposal: improve error descriptions (capitalize variables and respect prefix) #67

Open
tomkarw opened this issue Aug 3, 2022 · 1 comment

Comments

@tomkarw
Copy link

tomkarw commented Aug 3, 2022

Hey @softprops,
I encountered the problem of error accuracy when working with envy.

This issue seems vaguely relevant, but it's missing any description, so I decided to create a new one.

The problem

Basically given code like this

struct Env {
    pub some_var: String
}

fn main() {
    let _env = envy::prefixed("ABC_")
        .from_env::<Env>().unwrap();
}

I'm getting an error like this:

MissingValue("some_var")

where I'd like to see an error like this:

MissingValue("ABC_SOME_VAR")

Quick solution

I was able to overcome this in my project by a quick hack:

panic!("Missing value: ABC_{}", err.to_string().split_whitespace().last().unwrap().to_uppercase());

but obviously it would be better if envy just had nicer errors in the first place.

Proposal

I would be happy to introduce a PR, improving the error messages and adjusting the behavior for prefixed variables. Let me know if you're interested in seeing this, is the proposed improvement acceptable, and I'll work on it.

@flxdot
Copy link

flxdot commented Apr 29, 2023

I just stumbled across the same issue and wrote a thin wrapper around it:

use serde::de::DeserializeOwned;

#[derive(Debug)]
pub enum FromEnvError {
    MissingValue(String),
    Custom(String),
}

pub trait FromEnv: DeserializeOwned {
    fn from_env(prefix: &str) -> Result<Self, FromEnvError> {
        match envy::prefixed(prefix).from_env::<Self>() {
            Ok(config) => Ok(config),
            Err(error) => match error {
                envy::Error::MissingValue(key) => {
                    Err(FromEnvError::MissingValue(format!(
                        "Missing environment variable: {}{}",
                        prefix,
                        key.to_uppercase().as_str()
                    )))
                }
                envy::Error::Custom(error) => Err(FromEnvError::Custom(format!(
                    "Failed to load config from environment: {}",
                    error
                ))),
            },
        }
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants