From f215e67944baf32936365e02196ac4e9307a3ad6 Mon Sep 17 00:00:00 2001 From: Benjamin Dauvergne Date: Sat, 12 Jan 2019 13:48:56 +0100 Subject: [PATCH] jsonresponse: use string conversion on exceptions (fixes #29060) - introduce exception_to_text(): - first try to use unicode/str on exception - then try to use repr, - finally only render class name and e.args (if present) --- passerelle/utils/jsonresponse.py | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/passerelle/utils/jsonresponse.py b/passerelle/utils/jsonresponse.py index 6dfb50a..68464e1 100644 --- a/passerelle/utils/jsonresponse.py +++ b/passerelle/utils/jsonresponse.py @@ -2,6 +2,7 @@ # django-jsonresponse (https://github.com/jjay/django-jsonresponse) distributed # under BSD license +import six import datetime import json import functools @@ -33,6 +34,24 @@ class APIError(RuntimeError): super(APIError, self).__init__(*args) +def exception_to_text(e): + try: + return six.text_type(e) + except Exception: + pass + + try: + return six.text_type(repr(e)) + except Exception: + pass + + try: + content = six.text_type(repr(e.args)) if e.args != [] else '' + except Exception: + content = '' + return u'%s(%s)' % (e.__class__.__name__, content) + + class JSONEncoder(DjangoJSONEncoder): def default(self, o): if isinstance(o, time.struct_time): @@ -125,7 +144,7 @@ class to_json(object): data = self.obj_to_response(req, resp) status = 200 except Exception as e: - extras = {'method': req.method, 'exception': repr(e)} + extras = {'method': req.method, 'exception': exception_to_text(e)} if not self.logger: extras['request'] = req if req.method == 'POST': -- 2.20.1