在django中优雅处理全局异常并规范api返回,核心做法是编写自定义中间件或配置`handler404`/`handler500`视图,统一捕获未处理的异常,并将其转换为符合restful规范的json响应。具体实现时,需定义一个统一的错误码和消息结构(如包含`code`、`message`、`data`字段),在中间件中拦截`exception`,记录日志后返回标准格式的http 200或对应状态码的json数据。这样做的结果是前端无需针对每种错误编写特殊的解析逻辑,后端也能保持业务代码的整洁,专注于正常流程的处理。

Django默认异常处理机制存在哪些不足
Django默认的异常处理机制主要面向Web页面渲染,对于API场景不够友好。当发生`Http404`或`PermissionDenied`时,Django会尝试渲染模板,若未配置模板则抛出`TemplateDoesNotExist`,导致最终返回的是HTML错误页而非JSON。此外,对于未捕获的业务异常(如`ValueError`、`KeyError`),Django会触发内部服务器错误(500)并展示调试页面,暴露敏感信息且无法被客户端正确解析。这种机制缺乏统一的错误码体系和结构化输出,迫使开发者在每个视图层手动try-catch,增加了代码冗余和维护成本。

from django.http import JsonResponse
from django.core.exceptions import PermissionDenied
from django.http import Http404
def custom_json_response(data=None, code=200, message='success', status=200):
"""统一API返回格式"""
return JsonResponse({
'code': code,
'message': message,
'data': data
}, status=status)
def handle_api_exception(request, exception):
"""全局异常处理视图"""
if isinstance(exception, Http404):
return custom_json_response(code=404, message='Not Found', status=404)
elif isinstance(exception, PermissionDenied):
return custom_json_response(code=403, message='Forbidden', status=403)
else:
# 记录日志
import logging
logger = logging.getLogger(__name__)
logger.error(f'Unhandled exception: {str(exception)}', exc_info=True)
return custom_json_response(code=500, message='Internal Server Error', status=500)如何构建统一的全局异常中间件
构建全局异常中间件是实现规范化返回的关键步骤。中间件需要在`process_exception`钩子中捕获视图层抛出的所有异常。为了区分业务异常和系统异常,可以定义一个基类`ApiException`,所有业务错误都继承自该类。在中间件中,判断异常类型:若是`ApiException`,提取其自定义的错误码和消息;若是其他异常,则视为系统错误。中间件返回标准的`JsonResponse`对象,从而覆盖Django默认的响应生成逻辑。这种方式将异常处理逻辑从视图层剥离,实现了关注点分离。
Nodriver是Undetected-Chromedriver的官方继承者,提供异步浏览器自动化功能,可直接与Chrome DevTools Protocol通信,无需Selenium或WebDriver依赖。专为规避反机器人系统(包括Cloudflare和Imperva)的隐蔽网络自动化而构建。
立即学习“Python免费学习笔记(深入)”;

import json
import logging
from django.http import JsonResponse
class ApiException(Exception):
def __init__(self, code, message):
self.code = code
self.message = message
super().__init__(self.message)
class GlobalExceptionMiddleware:
def __init__(self, get_response):
self.get_response = get_response
self.logger = logging.getLogger(__name__)
def __call__(self, request):
response = self.get_response(request)
return response
def process_exception(self, request, exception):
if isinstance(exception, ApiException):
return JsonResponse({
'code': exception.code,
'message': exception.message,
'data': None
}, status=200) # 业务错误通常返回200,由code区分
# 系统异常
self.logger.error(f'Global Exception: {str(exception)}', exc_info=True)
return JsonResponse({
'code': 500,
'message': 'Internal Server Error',
'data': None
}, status=500)如何在视图中使用自定义异常类
在视图中使用自定义异常类,可以让业务逻辑更清晰地表达错误意图。例如,在用户注册接口中,如果用户名已存在,不应抛出通用的`ValueError`,而应抛出`ApiException(code=1001, message='Username already exists')`。调用方只需raise这个异常,无需关心具体的HTTP状态码或JSON序列化过程,这些都由中间件统一处理。这种做法使得视图代码更加简洁,只关注业务规则的判断,而将错误呈现的逻辑交给基础设施层。同时,通过定义不同的错误码,前端可以根据`code`进行精确的错误提示,提升用户体验。

















