djangodjango-rest-frameworkdjango-errors

using Handler404 in django url dispatcher cause server error


I followed this https://stackoverflow.com/a/31381075/10087274 because I want when url does not exist a json shows error but the problem is here that I get server error 500 when I add handler404 in my url dispatcher here is my project url :

from django.urls import path, include
from django.conf.urls import handler404
from api.exception import custom404

handler404 = custom404

urlpatterns = [
    path('api/v1/', include('acl.urls')),
]

and I have exception.py inside my project folder (near settings.py) contains this:

from django.http import JsonResponse


def custom404(request):
    return JsonResponse({
        'status_code': 404,
        'error': 'The resource was not found'
    })

I dont know how can I solve my problem


Solution

  • Unfortunately, you haven't provided much information regarding the error traceback.

    Anyway, The very first thing I noticed in your code, you've missed one optional parameter to the custom404 function. That function should take two parameters, request and exception

    def custom404(request, exception=None):
        response = {
            'status_code': 404,
            'error': 'The resource was not found'
        }
        return JsonResponse(response, status=404)

    Reference
    1. Custom Error Views