Before I try to make this work, I wondered if anyone had tried this, whether it was a good idea or not, etc.
I find myself doing this a lot:
if some_result is None:
try:
raise ResultException
except ResultException:
logger.exception(error_msg)
raise ResultException(error_msg)
I would rather try this:
if some_result is None:
with ResultException:
logger.exception(error_msg)
Where the __exit__() statement would always raise the exception in the context.
Would this be clearer? Is this possible?
I only ask because I imagine someone else has tried this, or at least attempted it. But I don't seem to find any common patterns for accomplishing this after doing a couple of Google searches.
UPDATE
Here's some more information on this particular issue.
I have a method that goes to a database and determines what the user's id is via their email. The problem is that if the user isn't found, it'll return None. This is okay for most calls, but when it's incorporated in higher-level methods, this can happen:
def change_some_setting(setting, email):
user_id = user_id_by_email(email) # None
_change_some_setting(setting, id)
Now when _change_some_setting attempts to change the setting for a user who's id is None, we get a very vague ProgrammingException from the database library.
This helps prevent that. Is there a better way?
user_id_by_emailshould raise an exception, as @JanneKarila said in his answer (however creating a wrapper is only acceptable if you really can't changeuser_id_by_email). \$\endgroup\$