Skip to content

Commit

Permalink
Merge pull request #102 from benkuhn/safer_repr
Browse files Browse the repository at this point in the history
Don't die while serializing a stack trace if __repr__ throws
  • Loading branch information
coryvirok committed Mar 22, 2016
2 parents 61290db + 9449d0e commit 9515bb3
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 14 deletions.
40 changes: 26 additions & 14 deletions rollbar/lib/transforms/serializable.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,21 +75,33 @@ def transform_custom(self, o, key=None):
if o is None:
return None

if any(filter(lambda x: isinstance(o, x), self.whitelist)):
try:
return repr(o)
except TypeError:
pass

# If self.safe_repr is False, use repr() to serialize the object
if not self.safe_repr:
# Best to be very careful when we call user code in the middle of
# preparing a stack trace. So we put a try/except around it all.
try:
if any(filter(lambda x: isinstance(o, x), self.whitelist)):
try:
return repr(o)
except TypeError:
pass

# If self.safe_repr is False, use repr() to serialize the object
if not self.safe_repr:
try:
return repr(o)
except TypeError:
pass

# Otherwise, just use the type name
return str(type(o))

except Exception as e:
exc_str = ''
try:
return repr(o)
except TypeError:
pass

# Otherwise, just use the type name
return str(type(o))
exc_str = str(e)
except Exception as e2:
exc_str = '[%s while calling str(%s)]' % (e2.__class__.__name__, e.__class__.__name__)
return '<%s in %s.__repr__: %s>' % (
e.__class__.__name__, o.__class__.__name__, exc_str)


__all__ = ['SerializableTransform']
25 changes: 25 additions & 0 deletions rollbar/test/test_serializable_transform.py
Original file line number Diff line number Diff line change
Expand Up @@ -218,3 +218,28 @@ def __repr__(self):
expected['custom'] = SNOWMAN
self._assertSerialized(start, expected, whitelist=[CustomRepr])

def test_encode_with_bad_repr_doesnt_die(self):
class CustomRepr(object):
def __repr__(self):
assert False

start = {'hello': 'world', 'custom': CustomRepr()}
serializable = SerializableTransform(whitelist_types=[CustomRepr])
result = transforms.transform(start, [serializable])
self.assertRegex(result['custom'], "<AssertionError.*CustomRepr.*>")

def test_encode_with_bad_str_doesnt_die(self):

class UnStringableException(Exception):
def __str__(self):
raise Exception('asdf')

class CustomRepr(object):

def __repr__(self):
raise UnStringableException()

start = {'hello': 'world', 'custom': CustomRepr()}
serializable = SerializableTransform(whitelist_types=[CustomRepr])
result = transforms.transform(start, [serializable])
self.assertRegex(result['custom'], "<UnStringableException.*Exception.*str.*>")

0 comments on commit 9515bb3

Please sign in to comment.