[Django]-How to stop Django Rest Framework from rendering html for exceptions

0👍

The error can’t in api_view.

This can be a configuration error. Check the configuration files. Check your ALLOWED_HOSTS.

See: https://docs.djangoproject.com/en/1.10/ref/settings/#std:setting-ALLOWED_HOSTS.

0👍

I don’t know if this is the best way to handle this, but by adding the custom DRF exception handler below, an unhandled exception will now have a standard json format.

def custom_exception_handler(exc, context):
    # Call REST framework's default exception handler first
    # to get the standard error response.
    response = exception_handler(exc, context)

    # response == None is an exception not handled by the DRF framework in the call above
    if response is not None:
        response.data['status_code'] = response.status_code
    else:
        response = Response({'detail': 'Unhandled server error'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        response.data['status_code'] = 500

        set_rollback()

    return response
👤Stuart

Leave a comment