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



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

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

    return Response({'error': False})


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)


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'


# 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.


As you can see in the documentation.

All you need to do is configure settings.

    '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)
        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.


Leave a comment