user907988
user907988

Reputation: 645

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

Upvotes: 1

Views: 383

Answers (2)

FAYEMI BOLUWATIFE
FAYEMI BOLUWATIFE

Reputation: 118

Well django rest framework is open source, so if you want to replicate certain behaviour you can read the code and pick and chose what you like. For instance, you can see that the Generic Error view (custom server and bad request error views) provided in drf docs are located inside exceptions.py inside rest_framework you can look it up here and see how it can be done.

Create a custom 404 view, like this:

def not_found(request, exception, *args, **kwargs):
    """ Generic 404 error handler """
    data = {
        'error': 'Not Found (404)'
    }
    return JsonResponse(data, status=status.HTTP_404_NOT_FOUND)
    

Upvotes: 0

JPG
JPG

Reputation: 88639

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

Upvotes: 2

Related Questions