import logging import datetime from rest_framework.views import exception_handler as rest_handler from django.db import DatabaseError from redis.exceptions import RedisError from rest_framework.response import Response from rest_framework import status logger = logging.getLogger("drf") def exception_handler(exc, context): """ :param exc: 异常 :param context: 上下文 :return: Response object """ response = rest_handler(exc, context) context_view = context.get("view", None) context_path = context.get(‘request‘).path context_method = context.get(‘request‘).method context_ip = context.get(‘request‘).META.get("REMOTE_ADDR") if response is None: if isinstance(exc, DatabaseError) or isinstance(exc, RedisError) or isinstance(exc, (KeyError, AttributeError)): logger.error(‘[ERROR] %s %s,%s‘ % (datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),context_view, exc)) custom_response = Response( {‘success‘: False, ‘msg‘: {‘DatabaseError or RedisError‘:str(exc).replace(‘\\‘,‘‘)}, "status": status.HTTP_500_INTERNAL_SERVER_ERROR, "path": context_path, "method": context_method, ‘remote_address‘: context_ip}) return custom_response exc_detail, exc_code = exc.message, exc.status_code custom_response = Response({"success": False, "msg": exc_detail, "code": exc_code, "path": context_path, "method": context_method, ‘remote_address‘: context_ip }) return custom_response
setting.py注册handler,
Response bodyDownload
|
django restframework 全局异常处理,编写自定义custom_exception_handler
原文:https://www.cnblogs.com/SunshineKimi/p/14330068.html