-
Notifications
You must be signed in to change notification settings - Fork 300
/
Copy pathexceptions.py
74 lines (64 loc) · 2.56 KB
/
exceptions.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import inspect
from django.utils import six, encoding
from django.utils.translation import ugettext_lazy as _
from rest_framework import status, exceptions
from rest_framework.views import exception_handler as drf_exception_handler
from rest_framework_json_api.utils import format_value
def exception_handler(exc, context):
response = drf_exception_handler(exc, context)
if not response:
return response
errors = []
# handle generic errors. ValidationError('test') in a view for example
if isinstance(response.data, list):
for message in response.data:
errors.append({
'detail': message,
'source': {
'pointer': '/data',
},
'status': encoding.force_text(response.status_code),
})
# handle all errors thrown from serializers
else:
for field, error in response.data.items():
field = format_value(field)
pointer = '/data/attributes/{}'.format(field)
# see if they passed a dictionary to ValidationError manually
if isinstance(error, dict):
errors.append(error)
elif isinstance(error, six.string_types):
classes = inspect.getmembers(exceptions, inspect.isclass)
# DRF sets the `field` to 'detail' for its own exceptions
if isinstance(exc, tuple(x[1] for x in classes)):
pointer = '/data'
errors.append({
'detail': error,
'source': {
'pointer': pointer,
},
'status': encoding.force_text(response.status_code),
})
elif isinstance(error, list):
for message in error:
errors.append({
'detail': message,
'source': {
'pointer': pointer,
},
'status': encoding.force_text(response.status_code),
})
else:
errors.append({
'detail': error,
'source': {
'pointer': pointer,
},
'status': encoding.force_text(response.status_code),
})
context['view'].resource_name = 'errors'
response.data = errors
return response
class Conflict(exceptions.APIException):
status_code = status.HTTP_409_CONFLICT
default_detail = _('Conflict.')