如何在REST Framework中返回JSON格式的404错误而非HTML?
实现Django REST Framework 404错误返回JSON格式
你遇到的问题是自定义异常处理器未生效,核心原因是未在DRF配置中指定自定义处理器路径,且没有覆盖DRF自身的NotFound异常(和Django原生Http404为不同异常类)。按以下步骤修改即可解决:
1. 在项目配置中指定自定义异常处理器
打开settings.py,找到或新建REST_FRAMEWORK配置块,添加EXCEPTION_HANDLER指向你的自定义函数:
REST_FRAMEWORK = { 'EXCEPTION_HANDLER': '你的应用名.views.custom_exception_handler' }
2. 修正自定义异常处理函数
DRF内部抛出的404异常是rest_framework.exceptions.NotFound,而非Django原生的Http404,需要同时处理这两种异常:
from rest_framework.views import exception_handler from rest_framework.response import Response from rest_framework import status from django.http import Http404 from rest_framework.exceptions import NotFound def custom_exception_handler(exc, context): # 先调用DRF默认处理器,获取其他异常的标准响应 response = exception_handler(exc, context) # 统一处理原生Http404和DRF的NotFound异常 if isinstance(exc, (Http404, NotFound)): return Response({"error": "页面未找到"}, status=status.HTTP_404_NOT_FOUND) # 其他异常返回默认处理结果 return response
3. 处理全局非API路由的404(可选)
如果需要让访问非API路由的404也返回JSON,在项目根目录的urls.py中自定义404视图:
from django.http import JsonResponse def custom_global_404(request, exception): return JsonResponse({"error": "页面未找到"}, status=404) handler404 = custom_global_404
内容的提问来源于stack exchange,提问作者Mohamed Mohsen
相关产品推荐
相关产品推荐

