Skip to main content

dotenv/
error.rs

1use std::env;
2use std::error;
3use std::fmt;
4use std::io;
5
6/// Errors that can occur when working with dotenv files.
7#[derive(Debug)]
8#[non_exhaustive]
9pub enum Error {
10    /// An I/O error, e.g. file not found or permission denied.
11    Io(io::Error),
12    /// An environment variable error, e.g. non-unicode value.
13    Env(env::VarError),
14}
15
16impl Error {
17    /// Returns `true` if this error was caused by a file not being found.
18    pub fn is_not_found(&self) -> bool {
19        if let Error::Io(err) = self {
20            return err.kind() == io::ErrorKind::NotFound;
21        }
22
23        false
24    }
25
26    pub(crate) fn not_found() -> Self {
27        io::Error::new(io::ErrorKind::NotFound, "path not found").into()
28    }
29}
30
31impl fmt::Display for Error {
32    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
33        match self {
34            Error::Io(err) => err.fmt(fmt),
35            Error::Env(err) => err.fmt(fmt),
36        }
37    }
38}
39
40impl error::Error for Error {
41    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
42        match self {
43            Error::Io(err) => Some(err),
44            Error::Env(err) => Some(err),
45        }
46    }
47}
48
49impl From<io::Error> for Error {
50    fn from(err: io::Error) -> Self {
51        Error::Io(err)
52    }
53}
54
55impl From<env::VarError> for Error {
56    fn from(err: env::VarError) -> Self {
57        Error::Env(err)
58    }
59}