Added generic 500 and 400 JSON error handlers.

This commit is contained in:
Carlton Gibson 2018-03-27 12:02:32 +02:00
parent a95cffc73e
commit 51760a6ed8
2 changed files with 39 additions and 2 deletions

View File

@ -8,6 +8,7 @@ from __future__ import unicode_literals
import math
from django.http import JsonResponse
from django.utils import six
from django.utils.encoding import force_text
from django.utils.translation import ugettext_lazy as _
@ -235,3 +236,23 @@ class Throttled(APIException):
wait))))
self.wait = wait
super(Throttled, self).__init__(detail, code)
def server_error(request, *args, **kwargs):
"""
Generic 500 error handler.
"""
data = {
'error': 'Server Error (500)'
}
return JsonResponse(data, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
def bad_request(request, exception, *args, **kwargs):
"""
Generic 400 error handler.
"""
data = {
'error': 'Bad Request (400)'
}
return JsonResponse(data, status=status.HTTP_400_BAD_REQUEST)

View File

@ -1,11 +1,12 @@
from __future__ import unicode_literals
from django.test import TestCase
from django.test import RequestFactory, TestCase
from django.utils import six, translation
from django.utils.translation import ugettext_lazy as _
from rest_framework.exceptions import (
APIException, ErrorDetail, Throttled, _get_error_details
APIException, ErrorDetail, Throttled, _get_error_details, bad_request,
server_error
)
@ -87,3 +88,18 @@ class TranslationTests(TestCase):
# this test largely acts as a sanity test to ensure the translation files are present.
self.assertEqual(_('A server error occurred.'), 'Une erreur du serveur est survenue.')
self.assertEqual(six.text_type(APIException()), 'Une erreur du serveur est survenue.')
def test_server_error():
request = RequestFactory().get('/')
response = server_error(request)
assert response.status_code == 500
assert response["content-type"] == 'application/json'
def test_bad_request():
request = RequestFactory().get('/')
exception = Exception('Something went wrong — Not used')
response = bad_request(request, exception)
assert response.status_code == 400
assert response["content-type"] == 'application/json'