异常响应配置

异常响应配置

封装项目异常处理

utils/exception.py

from rest_framework.views import exception_handler as drf_exception_handler
from rest_framework.views import Response
from rest_framework import status
from utils.logging import logger
def exception_handler(exc, context):
    response = drf_exception_handler(exc, context)
    # 异常模块就是记录项目的错误日志
    logger.error('%s - %s - %s' % (context['view'], context['request'].method, exc))
    if response is None:
        return Response({
            'detail': '%s' % exc
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR, exception=True)
    return response

dev.py配置

# drf配置
REST_FRAMEWORK = {
    'EXCEPTION_HANDLER': 'utils.exception.exception_handler',
    #渲染模块的全局配置:开发一般只配置json,为了安全和保密技术
    'DEFAULT_RENDERER_CLASSES':[
        'rest_framework.renderers.JSONRenderer',
    ]
}

二次封装Response模块

utils/response.py

from rest_framework.response import Response

class APIResponse(Response):
    def __init__(self, data_status=0, data_msg='ok', results=None, http_status=None, headers=None, exception=False, **kwargs):
        data = {
            'status': data_status,
            'msg': data_msg,
        }
        if results is not None:
            data['results'] = results
        data.update(kwargs)

        super().__init__(data=data, status=http_status, headers=headers, exception=exception)
posted @ 2019-12-01 15:31  chanyuli  阅读(122)  评论(0编辑  收藏  举报