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

我try 了下面的代码,但它对我不起作用

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

推荐答案

我创造了同样的东西,它对我来说效果很好

目录路径100

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',
}

Django相关问答推荐

未显示SWAGER上的一些示例架构

对象Django API中的对象

如何在Django上创建ManyToMany管理面板?

注册新用户时,对象没有属性';is_active';错误:';NoneType';对象没有属性

我如何获得已循环的每个项目的名称?

data._mutable= 在 Django REST 框架中为真

Django 从 url 保存图像并与 ImageField 连接

可以在基于 Django 类的视图中设置实例变量吗?

Django 自定义管理器 - 如何仅返回登录用户创建的对象?

Django 从字段开始

Django,如何从模型表单的 Select 字段中删除空白 Select ?

无效的命令 WSGIDaemonProcess 在 CentOS 6.7 上部署 Django 应用程序

是否可以将 FastAPI 与 Django 一起使用?

Django 删除未使用的媒体文件

超过 1 个外键

从基于类的通用视图中获取 request.session

如何在 Django 1.9 中删除 DB (sqlite3) 以从头开始?

在 Django 中使用 LiveServerTestCase 时使用代码登录

Django Rest Framework 序列化程序中的循环依赖

Django 模型方法 - create_or_update