How to decouple application from exceptions that creep in from used library dependencies?
[app] --uses--> [lib] --dependson--> [dependency]
/ /
x- <-propagates--o <---throwsexception--' /
\ /
`-----needstohandle,soimports-----> --'
The problem is from real pip code:
- module A (req/req_set.py) depends on module B
- module B (download) uses module C (requests)
- module A imports module C to handle exception from C
How to encapsulate exception in module B? To remove dependency on C from module A? How to make sure that the cause and details of original exception are not lost? In other words how can I reraise the exception with a different name?
The snippet below does what is needed, but it it Python 3 only:
try:
dependency_call()
except DependencyError as exc:
raise LibraryError from exc
UPDATE: I am looking for Python 2 compatible solution, the Python 3 added raise ... from ... that does the trick almost good.
UPDATE 2: The goal of encapsulating exception is to catch it in [lib] and re-throw a new one to [app] preserving the stack trace so that debug tools can still walk up the code (for human-only solution the answer by Alex Thornton should be good).