| 1 |
import copy |
| 2 |
import os |
| 3 |
import binascii |
| 4 |
import logging |
| 5 |
|
| 6 |
from ..utils.compat import string_types |
| 7 |
|
| 8 |
log = logging.getLogger(__name__) |
| 9 |
|
| 10 |
|
| 11 |
class Throwable(object): |
| 12 |
""" |
| 13 |
An object recording exception infomation under trace entity |
| 14 |
`cause` section. The information includes the stack trace, |
| 15 |
working directory and message from the original exception. |
| 16 |
""" |
| 17 |
def __init__(self, exception, stack, remote=False): |
| 18 |
""" |
| 19 |
:param Exception exception: the catched exception. |
| 20 |
:param list stack: the formatted stack trace gathered |
| 21 |
through `traceback` module. |
| 22 |
:param bool remote: If False it means it's a client error |
| 23 |
instead of a downstream service. |
| 24 |
""" |
| 25 |
self.id = binascii.b2a_hex(os.urandom(8)).decode('utf-8') |
| 26 |
|
| 27 |
try: |
| 28 |
message = str(exception) |
| 29 |
# in case there is an exception cannot be converted to str |
| 30 |
except Exception: |
| 31 |
message = None |
| 32 |
|
| 33 |
# do not record non-string exception message |
| 34 |
if isinstance(message, string_types): |
| 35 |
self.message = message |
| 36 |
|
| 37 |
self.type = type(exception).__name__ |
| 38 |
self.remote = remote |
| 39 |
|
| 40 |
try: |
| 41 |
self._normalize_stack_trace(stack) |
| 42 |
except Exception: |
| 43 |
self.stack = None |
| 44 |
log.warning("can not parse stack trace string, ignore stack field.") |
| 45 |
|
| 46 |
if exception: |
| 47 |
setattr(exception, '_recorded', True) |
| 48 |
setattr(exception, '_cause_id', self.id) |
| 49 |
|
| 50 |
def _normalize_stack_trace(self, stack): |
| 51 |
if not stack: |
| 52 |
return None |
| 53 |
|
| 54 |
self.stack = [] |
| 55 |
|
| 56 |
for entry in stack: |
| 57 |
path = entry[0] |
| 58 |
line = entry[1] |
| 59 |
label = entry[2] |
| 60 |
if 'aws_xray_sdk/' in path: |
| 61 |
continue |
| 62 |
|
| 63 |
normalized = {} |
| 64 |
normalized['path'] = os.path.basename(path).replace('\"', ' ').strip() |
| 65 |
normalized['line'] = line |
| 66 |
normalized['label'] = label.strip() |
| 67 |
|
| 68 |
self.stack.append(normalized) |
| 69 |
|
| 70 |
def __getstate__(self): |
| 71 |
properties = copy.copy(self.__dict__) |
| 72 |
|
| 73 |
if not self.stack: |
| 74 |
del properties['stack'] |
| 75 |
|
| 76 |
return properties |