Home > Enterprise >  How to return 404 and 500 errors in json formats instead of standard html pages in Django 4.x
How to return 404 and 500 errors in json formats instead of standard html pages in Django 4.x

Time:09-13

I found only very stale articles on the Internet that don't quite solve my problem.

I tried this way, but Django still returns html pages:

exceptions.py

def custom_exception_handler(exc, context):
    response = exception_handler(exc, context)

    if response is not None:
        if response.status_code == 500:
            response.data = {"code": 500, "message": "Internal server error"}
        if response.status_code == 404:
            response.data = {"code": 404, "message": "The requested resource was not found on this server"}
    return response

settings.py

REST_FRAMEWORK = {
    'EXCEPTION_HANDLER': 'backend.exceptions.custom_exception_handler',
}

CodePudding user response:

I think you'd just override the default templates..

I've override them using this in a view.py:

def handler404(request, exception):
    return render(request, 'custom_404.html', status=404)
def handler500(request):
    return render(request, 'custom_500.html', status=500)

That just seems to magically work, I really couldn't tell you how it knows to direct 500 to my handler.. it's not defined elsewhere in the project

and then for the template, custom_505.html, would look something like:

{{data}}
  • Related