rolodato/dotenv-safe

friendlier or custom error

alvaropinot opened this issue · 2 comments

It would be great if the error thrown at https://github.com/rolodato/dotenv-safe/blob/master/index.js#L32 could be custom or even a custom callback function.

so instead of a "ugly" error, a custom message could be printed.

this:

Error: Missing environment variables: URL
at Object.module.exports.config (node_modules/dotenv-safe/index.js:32:19)
at Object. (config/index.js:16:23)
at Module._compile (module.js:541:32)
at Object.Module._extensions..js (module.js:550:10)
at Module.load (module.js:458:32)
at tryModuleLoad (module.js:417:12)
at Function.Module._load (module.js:409:3)
at Module.runMain (module.js:575:10)
at run (node.js:348:7)
at startup (node.js:140:9)

could become this:

Please setup the variable URL at your .env file. You can use your env.example as a template.

maybe the callback function could be called with the missing variable and the original options
so we could write something like:

const config = dotenv.load((err) =>
  console.log(`Please setup the variables ${err.missing} at your .env file. 
    You can use your ${err.options.sample} as a template.`)
);

Hi @alvaropinot! Yes, I had considered this but didn't feel like implementing it at the time:

// Consider providing an Error class
:)

I'd like to keep the behavior as closest as possible to the original dotenv, so in this case we should throw a custom error (the original dotenv.load does not accept a callback function AFAIK, and any errors result in an exception). Would you mind sending a PR for this? Thanks!

You can now catch MissingEnvVarsError exceptions and get an array of missing environment variable names through err.missing. I'll make a new release once #15 is merged.