Suppose I have a dict
like:
envs = {
"prod": "PRODSERVERNAME",
"test": "TESTSERVERNAME",
"dev": "DEVSERVERNAME"
}
and I want to change the message the KeyError
returns, what I've been seeing in web articles on the subject is to print out the new message, like:
try:
server = envs[env]
except KeyError:
print(
f'No environment found for "{env}"; env must be one of the following: {", ".join(envs.keys())}'
)
It seems to me that I'd still want to throw appropriate error (in this case, KeyError
to be thrown), just with more helpful/specific information about that error. With that assumption (please correct me if there is a best practice around this), I'd implement that intention like:
try:
server = envs[env]
except KeyError:
raise KeyError(
f'No environment found for "{env}"; env must be one of the following: {", ".join(envs.keys())}'
)
But excepting an error only to throw the error of the same type seems inelegant at best, and janky at worst.
My question is: What is the appropriate way to handle situations like this? Is there any documentation I may have missed on best practices related to this topic?
Thanks in advance.