Projet

Général

Profil

0001-jsonresponse-use-string-conversion-on-exceptions-fix.patch

Benjamin Dauvergne, 14 janvier 2019 09:57

Télécharger (2,82 ko)

Voir les différences:

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 | 25 ++++++++++++++++++++++++-
 tests/test_base_adresse.py       |  1 +
 2 files changed, 25 insertions(+), 1 deletion(-)
passerelle/utils/jsonresponse.py
14 14
from django.core.exceptions import ObjectDoesNotExist, PermissionDenied
15 15
from django.core.serializers.json import DjangoJSONEncoder
16 16
from django.utils.translation import force_text
17
from django.utils import six
17 18

  
18 19
from requests.exceptions import RequestException
19 20

  
......
33 34
        super(APIError, self).__init__(*args)
34 35

  
35 36

  
37
def exception_to_text(e):
38
    try:
39
        return six.text_type(e)
40
    except Exception:
41
        pass
42

  
43
    try:
44
        return six.text_type(repr(e))
45
    except Exception:
46
        pass
47

  
48
    try:
49
        args = e.args
50
        try:
51
            content = six.text_type(repr(args)) if args != [] else ''
52
        except Exception:
53
            content = '<exception-while-rendering-args>'
54
    except AttributeError:
55
        content = ''
56
    return u'%s(%s)' % (e.__class__.__name__, content)
57

  
58

  
36 59
class JSONEncoder(DjangoJSONEncoder):
37 60
    def default(self, o):
38 61
        if isinstance(o, time.struct_time):
......
125 148
            data = self.obj_to_response(req, resp)
126 149
            status = 200
127 150
        except Exception as e:
128
            extras = {'method': req.method, 'exception': repr(e)}
151
            extras = {'method': req.method, 'exception': exception_to_text(e)}
129 152
            if not self.logger:
130 153
                extras['request'] = req
131 154
            if req.method == 'POST':
tests/test_base_adresse.py
86 86
    resp = app.get('/base-adresse/%s/search' % base_adresse.slug, status=400)
87 87
    assert resp.json['err'] == 1
88 88
    assert resp.json['err_class'] == 'passerelle.views.WrongParameter'
89
    assert resp.json['err_desc'] == u"missing parameters: 'q'."
89 90
    # json-api serializer
90 91
    resp = app.get('/base-adresse/%s/streets?zipcode=13400&coin=zz' % base_adresse.slug, status=400)
91 92
    assert resp.json['err'] == 1
92
-