mirror of
https://github.com/encode/django-rest-framework.git
synced 2024-11-10 19:56:59 +03:00
Use overridden settings exception handler
Instead of using the api_settings exception handler, we use the overridden settings attribute to find the correct handler. Closes #5054
This commit is contained in:
parent
5e6b233977
commit
c2ee1b3033
|
@ -290,7 +290,7 @@ class APIView(View):
|
|||
"""
|
||||
Returns the exception handler that this view uses.
|
||||
"""
|
||||
return api_settings.EXCEPTION_HANDLER
|
||||
return self.settings.EXCEPTION_HANDLER
|
||||
|
||||
# API policy implementation methods
|
||||
|
||||
|
|
|
@ -8,7 +8,7 @@ from django.test import TestCase
|
|||
from rest_framework import status
|
||||
from rest_framework.decorators import api_view
|
||||
from rest_framework.response import Response
|
||||
from rest_framework.settings import api_settings
|
||||
from rest_framework.settings import APISettings, api_settings
|
||||
from rest_framework.test import APIRequestFactory
|
||||
from rest_framework.views import APIView
|
||||
|
||||
|
@ -45,6 +45,19 @@ class ErrorView(APIView):
|
|||
raise Exception
|
||||
|
||||
|
||||
def custom_handler(exc, context):
|
||||
if isinstance(exc, SyntaxError):
|
||||
return Response({'error': 'SyntaxError'}, status=400)
|
||||
return Response({'error': 'UnknownError'}, status=500)
|
||||
|
||||
|
||||
class OverridenSettingsView(APIView):
|
||||
settings = APISettings({'EXCEPTION_HANDLER': custom_handler})
|
||||
|
||||
def get(self, request, *args, **kwargs):
|
||||
raise SyntaxError('request is invalid syntax')
|
||||
|
||||
|
||||
@api_view(['GET'])
|
||||
def error_view(request):
|
||||
raise Exception
|
||||
|
@ -118,3 +131,14 @@ class TestCustomExceptionHandler(TestCase):
|
|||
expected = 'Error!'
|
||||
assert response.status_code == status.HTTP_400_BAD_REQUEST
|
||||
assert response.data == expected
|
||||
|
||||
|
||||
class TestCustomSettings(TestCase):
|
||||
def setUp(self):
|
||||
self.view = OverridenSettingsView.as_view()
|
||||
|
||||
def test_get_exception_handler(self):
|
||||
request = factory.get('/', content_type='application/json')
|
||||
response = self.view(request)
|
||||
assert response.status_code == 400
|
||||
assert response.data == {'error': 'SyntaxError'}
|
||||
|
|
Loading…
Reference in New Issue
Block a user