[Django]-Django Rest Framework custom message for 404 errors

10👍

This solution affect all views:

Surely you can supply your custom exception handler: Custom exception handling

from rest_framework.views import exception_handler
from rest_framework import status

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)

    # Now add the HTTP status code to the response.
    if response.status_code == status.HTTP_404_NOT_FOUND:
        response.data['custom_field'] = 'some_custom_value'

    return response

Sure you can skip default rest_framework.views.exception_handler and make it completely raw.

Note: remember to mention your handler in django.conf.settings.REST_FRAMEWORK['EXCEPTION_HANDLER']

Solution for specific view:

from rest_framework.response import Response
# rest of the imports

class ProjectDetails(mixins.RetrieveModelMixin,
                     mixins.UpdateModelMixin,
                     generics.GenericAPIView):
    queryset = Project.objects.all()

    def handle_exception(self, exc):
        if isinstance(exc, Http404):
            return Response({'data': 'your custom response'}, 
                            status=status.HTTP_404_NOT_FOUND)

        return super(ProjectDetails, self).handle_exception(exc)

2👍

It’s possible by overriding specific methods like update, retrieve as:

from django.http import Http404
from rest_framework.response import Response


class ProjectDetails(mixins.RetrieveModelMixin,
                     mixins.UpdateModelMixin,
                     generics.GenericAPIView):
    queryset = Project.objects.all()

    def retrieve(self, request, *args, **kwargs):
        try:
            return super().retrieve(request, *args, **kwargs)
        except Http404:
            return Response(data={"cusom": "message"})

    def update(self, request, *args, **kwargs):
        try:
            return super().update(request, *args, **kwargs)
        except Http404:
            return Response(data={"cusom": "message"})
👤JPG

Leave a comment