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

add descriptive errors for var(..) #15

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
14 changes: 8 additions & 6 deletions dotenv/src/errors.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
#![allow(clippy::manual_non_exhaustive)]
use std::env;
use std::error;
use std::fmt;
Expand All @@ -9,7 +10,7 @@ pub type Result<T> = std::result::Result<T, Error>;
pub enum Error {
LineParse(String, usize),
Io(io::Error),
EnvVar(env::VarError),
EnvVar((env::VarError, String)),
#[doc(hidden)]
__Nonexhaustive,
}
Expand All @@ -27,7 +28,7 @@ impl error::Error for Error {
fn source(&self) -> Option<&(dyn error::Error + 'static)> {
match self {
Error::Io(err) => Some(err),
Error::EnvVar(err) => Some(err),
Error::EnvVar((err, _)) => Some(err),
_ => None,
}
}
Expand All @@ -37,7 +38,7 @@ impl fmt::Display for Error {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
match self {
Error::Io(err) => write!(fmt, "{}", err),
Error::EnvVar(err) => write!(fmt, "{}", err),
Error::EnvVar((err, msg)) => write!(fmt, "{}: {}", err, msg),
Error::LineParse(line, error_index) => write!(
fmt,
"Error parsing line: '{}', error at line index: {}",
Expand Down Expand Up @@ -65,7 +66,7 @@ mod test {

#[test]
fn test_envvar_error_source() {
let err = Error::EnvVar(env::VarError::NotPresent);
let err = Error::EnvVar((env::VarError::NotPresent, "TEST_VAR".to_string()));
let var_err = err
.source()
.unwrap()
Expand Down Expand Up @@ -104,11 +105,12 @@ mod test {

#[test]
fn test_envvar_error_display() {
let err = Error::EnvVar(env::VarError::NotPresent);
let var_name = "TEST_VAR".to_string();
let err = Error::EnvVar((env::VarError::NotPresent, var_name.clone()));
let var_err = env::VarError::NotPresent;

let err_desc = format!("{}", err);
let var_err_desc = format!("{}", var_err);
let var_err_desc = format!("{}: {}", var_err, var_name);
assert_eq!(var_err_desc, err_desc);
}

Expand Down
2 changes: 1 addition & 1 deletion dotenv/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ pub fn var<K: AsRef<OsStr>>(key: K) -> Result<String> {
START.call_once(|| {
dotenv().ok();
});
env::var(key).map_err(Error::EnvVar)
env::var(&key).map_err(|err| Error::EnvVar((err, key.as_ref().to_str().unwrap().into())))
}

/// Returns an iterator of `(key, value)` pairs for all environment variables of the current process.
Expand Down