[Fixed]-How disable return of HTML error page with django rest framework?

10πŸ‘

βœ…

One way of returning json would be to catch the exceptions and return proper response (assuming you’re using JSONParser as default parser):

from rest_framework.response import Response
from rest_framework import status


@api_view(['POST'])
@permission_classes((IsAuthenticated,))
def downloadData(request):
    try:
        print request.POST['tables']
    except:
        return Response({'error': True, 'content': 'Exception!'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    return Response({'error': False})

UPDATE

For global wise use-case the correct idea would be to put the json response in exception middleware.

You can find example in this blog post.

In your case you need to return DRF response, so if any exception gets raised it will end up in the process_exception:

from rest_framework.response import Response


class ExceptionMiddleware(object):

    def process_exception(self, request, exception):
        return Response({'error': True, 'content': exception}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
πŸ‘€mariodev

7πŸ‘

You can replace the default error handlers by specifying a custom handler in your URLConf as documented here

Something like this:

# In urls.py
handler500 = 'my_app.views.api_500'

and:

# In my_app.views
def api_500(request):
    response = HttpResponse('{"detail":"An Error Occurred"}', content_type="application/json", status=500)
    return response

I hope that helps.

4πŸ‘

As you can see in the documentation.

All you need to do is configure settings.

REST_FRAMEWORK = {
   'DEFAULT_AUTHENTICATION_CLASSES': (
       'rest_framework.authentication.TokenAuthentication',
       'rest_framework.parsers.JSONParser',
    ),
    'EXCEPTION_HANDLER': 'core.views.api_500_handler',
}

And pointing to a view that will recieve (exception, context)

Like this:

from rest_framework.views import exception_handler
...
def api_500_handler(exception, context):
    response = exception_handler(exception, context)
    try:
        detail = response.data['detail']
    except AttributeError:
        detail = exception.message
    response = HttpResponse(
        json.dumps({'detail': detail}),
        content_type="application/json", status=500
    )
    return response

My implementation is like this because if a expected rest framework exception is raised, like a β€˜exceptions.NotFoundβ€˜, exception.message will be empty. Thats why Im first calling to exception_handler of rest framework. If is an expected exception, I will get its message.

πŸ‘€Laraconda

Leave a comment