Django custom error handling when the url supplied does not match with any URL in ROOT_URLCONF

468 views Asked by At

How can I send a custom error message to front end when the endpoint coming from front end does not match with any URL in ROOT_URLCONF in settings.py. Currently if URL is not found in ROOT_URLCONF, a 403 error is raised and the entire html content is going in the error message.

How to send a custom error message in this case.

1

There are 1 answers

2
rossi On

You could have a custom error handler function returning a json string

def not_found_request(request, exception, *args, **kwargs):
"""
Generic 404 error handler.
"""
data = {
    'error': 'The requested endpoint does not exist'
}
return JsonResponse(data, status=status.HTTP_404_NOT_FOUND)

Then in your urlconf file you can set it to handler404 = 'not_found_request'