Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Added 'get_codes' and 'get_full_details'
  • Loading branch information
lovelydinosaur committed Oct 10, 2016
commit ce8eb7ecce73391a5de099ecad7ce83a83fa74be
27 changes: 26 additions & 1 deletion rest_framework/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
def _get_error_details(data, default_code=None):
"""
Descend into a nested data structure, forcing any
lazy translation strings or strings into `ErrorMessage`.
lazy translation strings or strings into `ErrorDetail`.
"""
if isinstance(data, list):
ret = [
Expand All @@ -43,6 +43,25 @@ def _get_error_details(data, default_code=None):
return ErrorDetail(text, code)


def _get_codes(detail):
if isinstance(detail, list):
return [_get_codes(item) for item in detail]
elif isinstance(detail, dict):
return {key: _get_codes(value) for key, value in detail.items()}
return detail.code


def _get_full_details(detail):
if isinstance(detail, list):
return [_get_full_details(item) for item in detail]
elif isinstance(detail, dict):
return {key: _get_full_details(value) for key, value in detail.items()}
return {
'message': detail,
'code': detail.code
}


class ErrorDetail(six.text_type):
"""
A string-like object that can additionally
Expand Down Expand Up @@ -99,6 +118,12 @@ def __init__(self, detail, code=None):
def __str__(self):
return six.text_type(self.detail)

def get_codes(self):
return _get_codes(self.detail)

def get_full_details(self):
return _get_full_details(self.detail)


class ParseError(APIException):
status_code = status.HTTP_400_BAD_REQUEST
Expand Down
12 changes: 2 additions & 10 deletions tests/test_validation_error.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,16 +30,8 @@ def setUp(self):
self.DEFAULT_HANDLER = api_settings.EXCEPTION_HANDLER

def exception_handler(exc, request):
return_errors = {}
for field_name, errors in exc.detail.items():
return_errors[field_name] = []
for error in errors:
return_errors[field_name].append({
'code': error.code,
'message': error
})

return Response(return_errors, status=status.HTTP_400_BAD_REQUEST)
data = exc.get_full_details()
return Response(data, status=status.HTTP_400_BAD_REQUEST)

api_settings.EXCEPTION_HANDLER = exception_handler

Expand Down