'Correct way to get a Python Exception object by name/string

I have a distributed system communicates using pub-sub model. The publishers are background services that should be long running. Subscribers are user applications that should stop and raise Exceptions when something is wrong. So error messages from the publisher are passed to subscribers in JSON messages such as:

"result": {
    "exc_type": "ValueError", 
    "exc_message": ["Error retrieving remote file. Response status: %s"], 
    "exc_module": "builtins"
}

In this example, I want the subscriber app to do something like

raise ValueError(f'error in publisher module {result["exc_module"]}, error message: {result["exc_message"]}')

What's the correct way to get the exception object from the string in "exc_type" field programmatically?

What I doing now is to call it from the Python __builtins__ dict:

x = __builtins__[result["exc_type"]]

But this seems like a hack rather than the appropriate way.

Thank you for any suggestions!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source