R
R
razielvamp2020-07-17 10:07:31
Django
razielvamp, 2020-07-17 10:07:31

How to customize server errors (response's) in Django and Django Rest Framework?

I have a ViewSet:

...
from handlers import specific_exception_handler...
...

class SomeViewSet(GenericViewSet):
    """
    Some custom generic viewset
    """
    queryset = SomeModel.objects.all()
    serializer_class = SomeSerializer
    parser_classes = (ParserClassThatReadSpecificXML,)
    renderer_classes = (RendererClassThatConvertResponseIntoSpecificXML,)

    def get_exception_handler(self):
        return specific_exception_handler_function_that_return_specific_xml_format_error

    @action(methods=['post'], detail=False, url_path='some_url', url_name='some_url')
    def register(self, request, format=None):

        some_variable = request.data.get('some_value', None)

        if not some_variable:
            raise ValueError

        return Response(data=some_variable, content_type="text/xml; charset=shift_jis")


i have render:

...
import xmltodict

class RendererClassThatConvertResponseIntoSpecificXML(BaseRenderer):
    media_type = 'text/xml'
    format = 'txt'
    charset = 'shift_jis'

    def render(self, data, media_type=None, renderer_context=None):
        # return data as non utf-8 xml string
        return xmltodict.unparse(data).encode("shift_jis")


I have an error handler:

...
from rest_framework.views import exception_handler

def specific_exception_handler_function_that_return_specific_xml_format_error(exc, context):

    response = exception_handler(exc, context)

    if response is not None:
        status_code = response.status_code
    else:
        status_code = status.HTTP_500_INTERNAL_SERVER_ERROR

    specific_data_that_will_be_converted_into_xml_by_render = {'ERROR_STATUS': status_code}
    headers = {'Retry-After': '300'}

    return Response(data, content_type='text/xml; charset=shift_jis', status=status_code, headers=headers)


Problem:

If an error occurs inside a View, such as ```raise ValueError```, then the client will receive an error message in XML format. Actually, what is required from the code, but
1. If an error occurs inside the render, then the user will be shown the standard ```500 Server Error``` message
2. If I try to open the URL outside of the View, then the client again the standard ```404 Server Error``` message will be displayed.

I need my XML formatted message to be sent by default anyway.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dr. Bacon, 2020-07-17
@bacon

500 status is when you can no longer do anything with an error and that means your XML will always be the same for such an error, just create a 500.html file with this xml and put it in the template path, with 404 the same way. But keep in mind that in DEBUG = True, they are not returned. https://docs.djangoproject.com/en/3.0/ref/views/#e... Well, or through overriding https://docs.djangoproject.com/en/dev/topics/http/...
PS on The DRF level also has its own views https://www.django-rest-framework.org/api-guide/ex...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question