|
1 | | -# Copyright 2016, Yahoo Inc. |
| 1 | +# Copyright 2019-2020, Kostis Anagnostopoulos; |
2 | 2 | # Licensed under the terms of the Apache License, Version 2.0. See the LICENSE file associated with the project for terms. |
3 | 3 | """:term:`jetsam` utility for annotating exceptions from ``locals()``. |
4 | 4 |
|
|
10 | 10 | >>> from graphtik.jetsam import * |
11 | 11 | >>> __name__ = "graphtik.jetsam" |
12 | 12 | """ |
13 | | - |
14 | 13 | import logging |
| 14 | +import sys |
| 15 | +from contextlib import contextmanager |
15 | 16 | from pathlib import Path |
16 | 17 |
|
17 | 18 | log = logging.getLogger(__name__) |
@@ -124,20 +125,38 @@ def save_jetsam(ex, locs, *salvage_vars: str, annotation="jetsam", **salvage_map |
124 | 125 | in case of errors:: |
125 | 126 |
|
126 | 127 |
|
127 | | - try: |
128 | | - a = 1 |
129 | | - b = 2 |
130 | | - raise Exception() |
131 | | - exception Exception as ex: |
132 | | - save_jetsam(ex, locals(), "a", b="salvaged_b", c_var="c") |
133 | | - raise |
| 128 | + >>> try: |
| 129 | + ... a = 1 |
| 130 | + ... b = 2 |
| 131 | + ... raise Exception("trouble!") |
| 132 | + ... except Exception as ex: |
| 133 | + ... save_jetsam(ex, locals(), "a", b="salvaged_b", c_var="c") |
| 134 | + ... raise |
| 135 | + Traceback (most recent call last): |
| 136 | + Exception: trouble! |
134 | 137 |
|
135 | 138 | And then from a REPL:: |
136 | 139 |
|
137 | | - import sys |
138 | | - sys.last_value.jetsam |
| 140 | + >>> import sys |
| 141 | + >>> sys.exc_info()[1].jetsam # doctest: +SKIP |
139 | 142 | {'a': 1, 'salvaged_b': 2, "c_var": None} |
140 | 143 |
|
| 144 | + .. Note:: |
| 145 | +
|
| 146 | + In order not to obfuscate the landing position of post-mortem debuggers |
| 147 | + in the case of errors, use the ``try-finally`` with ``ok`` flag pattern: |
| 148 | +
|
| 149 | + >>> ok = False |
| 150 | + >>> try: |
| 151 | + ... |
| 152 | + ... pass # do risky stuff |
| 153 | + ... |
| 154 | + ... ok = True # last statement in the try-body. |
| 155 | + ... except Exception as ex: |
| 156 | + ... if not ok: |
| 157 | + ... ex = sys.exc_info()[1] |
| 158 | + ... save_jetsam(...) |
| 159 | +
|
141 | 160 | ** Reason:** |
142 | 161 |
|
143 | 162 | Graphs may become arbitrary deep. Debugging such graphs is notoriously hard. |
|
0 commit comments