Skip to content

Commit

Permalink
Clearer tracebacks in case of chained exceptions (#2196)
Browse files Browse the repository at this point in the history
In case of exception, display a cleaner error traceback by hiding the `KeyError` bit deriving from a missed cache hit.

Signed-off-by: Giampaolo Rodola <[email protected]>
  • Loading branch information
giampaolo authored Jan 24, 2023
1 parent 2312057 commit 633d801
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 3 deletions.
10 changes: 10 additions & 0 deletions HISTORY.rst
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,18 @@
5.9.5 (IN DEVELOPMENT)
======================

**Enhancements**

- 2196_: in case of exception, display a cleaner error traceback by hiding the
`KeyError` bit deriving from a missed cache hit.

**Bug fixes**

- 2164_, [Linux]: compilation fails on kernels < 2.6.27 (e.g. CentOS 5).
- 2186_, [FreeBSD]: compilation fails with Clang 15. (patch by Po-Chuan Hsieh)
- 2191_, [Linux]: `disk_partitions()`_: do not unnecessarily read
/proc/filesystems and raise `AccessDenied`_ unless user specified `all=False`
argument.

5.9.4
=====
Expand Down
29 changes: 26 additions & 3 deletions psutil/_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -366,6 +366,20 @@ def __init__(self, seconds, pid=None, name=None):
# ===================================================================


# This should be in _compat.py rather than here, but does not work well
# with setup.py importing this module via a sys.path trick.
if PY3:
__builtins__["exec"]("""def raise_from(value, from_value):
try:
raise value from from_value
finally:
value = None
""")
else:
def raise_from(value, from_value):
raise value


def usage_percent(used, total, round_=None):
"""Calculate percentage usage of 'used' against 'total'."""
try:
Expand Down Expand Up @@ -407,7 +421,10 @@ def wrapper(*args, **kwargs):
try:
return cache[key]
except KeyError:
ret = cache[key] = fun(*args, **kwargs)
try:
ret = cache[key] = fun(*args, **kwargs)
except Exception as err:
raise raise_from(err, None)
return ret

def cache_clear():
Expand Down Expand Up @@ -452,11 +469,17 @@ def wrapper(self):
ret = self._cache[fun]
except AttributeError:
# case 2: we never entered oneshot() ctx
return fun(self)
try:
return fun(self)
except Exception as err:
raise raise_from(err, None)
except KeyError:
# case 3: we entered oneshot() ctx but there's no cache
# for this entry yet
ret = fun(self)
try:
ret = fun(self)
except Exception as err:
raise raise_from(err, None)
try:
self._cache[fun] = ret
except AttributeError:
Expand Down

0 comments on commit 633d801

Please sign in to comment.