Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which exception should be raised when a required environment variable is missing?

The title pretty much sums it up already.

I have a piece of code that calls os.getenv to get both a URL as well as a token in order to connect to a service. The code lives in a module and will only be imported from there, i.e. it's not a script.

It's not a huge issue at all, since I really only need to crash and display the message saying that there are unset values, but it got me thinking about which of Python's built-in exceptions would be the best fit.

I found the EnvironmentError, but that seems to function as base class from which IOError and other OS related exceptions inherit.

Would it be as simple as a ValueError, as it's really just a value that's missing?

Thanks!

like image 827
TomMP Avatar asked Feb 27 '20 14:02

TomMP


People also ask

What is the exception raised for an error that does not fall in any of the categories?

Raised when an error does not fall under any other category. Raised by next() function to indicate that there is no further item to be returned by iterator. Raised by parser when syntax error is encountered.

What is a raised exception?

Raising an exception is a technique for interrupting the normal flow of execution in a program, signaling that some exceptional circumstance has arisen, and returning directly to an enclosing part of the program that was designated to react to that circumstance.

What is raising exceptions in Python?

As a Python developer you can choose to throw an exception if a condition occurs. To throw (or raise) an exception, use the raise keyword.

Which package will be used to get the environment variables?

Environment variables are implemented through the os package, specifically os. environ.

Why is the environment variable not set?

If the error message states that the environment variable is not set, IT MEANS PRECISELY THAT ! The most likely reason is that your spelling of the variable name is WRONG.

Can I throw an exception for a missing configuration value?

It's your application- as long as you document it and clearly indicate the exception that will be thrown in the specific case of a missing configuration value, you can use any exception you like. If you do want a very specific indication of a missing value, you might consider writing your own ConfigurationSettingMissing exception:

What are the exceptions produced by the program?

Clarification: The exceptions are produced when anything unexpected happened. The program might not be able to find a file in the target location and hence program produces an exceptions. The exception produced, then terminates the program. 5. Which is the universal exception handler class?

Why should the exceptions always be given in proper sequence?

The exceptions should always be given in proper sequence to ensure that no code remains unreachable. If not done properly the code might never be used in a program. 14. Which class is used to handle the input and output exceptions? Clarification: There is a specific class to handle each type of exceptions that might be produced in a program.


4 Answers

You could always create a custom exception

https://www.programiz.com/python-programming/user-defined-exception https://docs.python.org/3/tutorial/errors.html

Ive used this guide before:

Something simple like

class UnconfiguredEnvironment(Exception):
    """base class for new exception"""
    pass

if not os.environ.get("URL",None):
    raise UnconfiguredEnvironment

Use the guides to extend as you see fit.

like image 137
tomgalpin Avatar answered Oct 21 '22 15:10

tomgalpin


Well most built in concrete exception classes are for specific use cases, and this one does not really fit in any but RuntimeError. But I would advise you to use a custom Exception subclass.

like image 23
Serge Ballesta Avatar answered Oct 21 '22 14:10

Serge Ballesta


By default KeyError is already raised when an environment variable doesn't exist. os.environ["THISENVDOESNTEXIST"]

Furthermore you can supply a default variable if the env variable doesn't exist. Doing this won't raise the error. os.environ.get("THISENVDOESNTEXIST", "defaultvalue")

Code executed:

Python 3.7.4 (tags/v3.7.4:e09359112e, Jul  8 2019, 20:34:20) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.environ["THISENVDOESNTEXIST"]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\Tin\AppData\Local\Programs\Python\Python37\lib\os.py", line 678, in __getitem__
    raise KeyError(key) from None
KeyError: 'THISENVDOESNTEXIST'
>>> os.environ.get("THISENVDOESNTEXIST", "defaultvalue")
'defaultvalue'

If you want to raise your own custom error you can do this:

class MyException(Exception):
  pass

try:
  os.environ["THISENVDOESNTEXIST"]
except KeyError as e:
  raise MyException("Tried accessing an environment variable that does not exist")
like image 20
Tin Nguyen Avatar answered Oct 21 '22 13:10

Tin Nguyen


You can make your own exceptions for specific cases by inheriting from Exception

class MissingEnvironmentVariable(Exception):
    pass


def get_my_env_var(var_name):
    try:
        envvar = os.environ[var_name]
    except KeyError:
        raise MissingEnvironmentVariable(f"{var_name} does not exist")
like image 26
Kathy Rindhoops Avatar answered Oct 21 '22 13:10

Kathy Rindhoops