Search code examples
djangorestdjango-rest-frameworkdjango-views

How to return the error in JSON format instead of HTML in REST framework?


I want to make an error handler exception to return the error 404 instead of this html. how can i do this ? enter image description here

i tried the following code but it didn't work for me

from rest_framework.views import exception_handler
from rest_framework.response import Response
from rest_framework import status
from django.http import Http404

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

    # Now add the HTTP 404 handling
    if isinstance(exc, Http404):
        custom_response_data = { "error": "page not found" }
        return Response(custom_response_data, status=status.HTTP_404_NOT_FOUND)

    # Return the default response if the exception handled is not a Http404
    return response


Solution

  • I create same things it's working fine for me

    directory path (myapp/custom_exception.py)

    from rest_framework.views import exception_handler
    
    
    def custom_exception_handler(exc, context):
        response = exception_handler(exc, context)
        if response.status_code == 404:
            response.data = {
                "success": False,
                "message": "Not found❗",
                "data": {}
            }
            return response
        elif response.status_code == 500:
            response.data = {
                "success": False,
                "message": "Internal server error! 🌐",
                "data": {}
            }
        # elif response.status_code == 400:
        #     response.data = {
        #         "success": False,
        #         "message": "Bad request!",
        #         "data": {}
        #     }
        elif response.status_code == 401:
            response.data = {
                "success": False,
                "message": "Login required! 🗝️",
                "data": {}
            }
        elif response.status_code == 403:
            response.data = {
                "success": False,
                "message": "Permission denied!",
                "data": {}
            }
    
        return response
    

    settings.py

    REST_FRAMEWORK = {
    
        'DEFAULT_AUTHENTICATION_CLASSES': [
            'rest_framework_simplejwt.authentication.JWTAuthentication',
        ],
    
        'DEFAULT_FILTER_BACKENDS': [
            'django_filters.rest_framework.DjangoFilterBackend',
        ],
    
        'EXCEPTION_HANDLER': 'myapp.custom_exception.custom_exception_handler',
    }