diff options
author | Giampaolo Rodola <g.rodola@gmail.com> | 2023-01-24 14:55:11 +0100 |
---|---|---|
committer | GitHub <noreply@github.com> | 2023-01-24 14:55:11 +0100 |
commit | 633d801919400b5c7524a21d19ae03ebed0f1929 (patch) | |
tree | b05305e2d201d8866fabd822cdda432256b2520a /psutil | |
parent | 2312057d267c85185e5f49eb86bb6f90bd9ab206 (diff) | |
download | psutil-633d801919400b5c7524a21d19ae03ebed0f1929.tar.gz |
Clearer tracebacks in case of chained exceptions (#2196)
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 <g.rodola@gmail.com>
Diffstat (limited to 'psutil')
-rw-r--r-- | psutil/_common.py | 29 |
1 files changed, 26 insertions, 3 deletions
diff --git a/psutil/_common.py b/psutil/_common.py index 387d9594..da8a96e5 100644 --- a/psutil/_common.py +++ b/psutil/_common.py @@ -366,6 +366,20 @@ class TimeoutExpired(Error): # =================================================================== +# 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: @@ -407,7 +421,10 @@ def memoize(fun): 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(): @@ -452,11 +469,17 @@ def memoize_when_activated(fun): 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: |