I'm using a library that will return something like the following when calling one of their functions
result = getResult(foo)
print(result)
The result is a dict
{'errorMessage': "name 'foo' is not defined", 'errorType': 'NameError'}
I want to raise a NameError
exception, but the following doesn't work
raise result['errorType'](result['errorMessage'])
It gives a new error
TypeError: 'str' object is not callable
How can I raise an exception who's type is defined from a string variable?
The value of result["errorType"]
is a string that names an error class, not the error class itself.
If the error type will always be a built-in type, you can look it up in __builtins__
.
raise getattr(__builtins__, result['errorType'])(result['errorMessage'])
You could use eval
but carefully:
>>> raise eval(f"{result['errorType']}(\"{result['errorMessage']}\")")
NameError: name 'foo' is not defined
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With