I have exception handling code that is copied and pasted in multiple places, e.g.
def get(self, id):
try:
response = self.client_module_property.get(id)
except APIItemNotFoundException:
print("'{}' does not exist.".format(id), file=sys.stderr)
sys.exit(1)
except Exception as e:
print(
"Unknown error. To debug run with env var LOG_LEVEL=DEBUG",
file=sys.stderr,
)
_log.error(e)
sys.exit(1)
...
And ...
def delete(self, id):
try:
self.client_module_property.delete(id=id)
except APIItemNotFoundException:
print("'{}' does not exist".format(id), file=sys.stderr)
sys.exit(1)
except Exception as e:
print(
"Unknown error. To debug run with env var LOG_LEVEL=DEBUG",
file=sys.stderr,
)
_log.error(e)
sys.exit(1)
I have investigated decorators but they are NOT a good option for me because I'm introspecting the function parameters in some other code and the decorators change the method signature.
Is there another way I can extract the exception handling code to be reusable?
The comments in this question suggest that context manager could be used here, but I'm not clear what this would look like from browsing the python docs.
The solution needs to work on Python 2.7 and 3.x