restframework的异常处理

一、默认可用异常处理

REST_FRAMEWORK = {
    'EXCEPTION_HANDLER': 'rest_framework.views.exception_handler'
}

二、自定义异常处理

2.1、参考学习的

from rest_framework import status
from django.db import DatabaseError
from rest_framework.views import exception_handler

def custom_exception_handler(exc, context):
    # 调用REST framework默认的异常处理方法获得标准错误响应对象,None无异常,not None有错误
    response = exception_handler(exc, context)
    if response is None:
        view = context['view']
        if isinstance(exc, DatabaseError):  # 追加数据库的异常判定
            print('[%s]: %s' % (view, exc))
            response = Response({'detail': '服务器内部错误'}, status=status.HTTP_507_INSUFFICIENT_STORAGE)	
    return response

2.2、自我修正的

import traceback
from rest_framework import status
from django.db import DatabaseError
from rest_framework.views import exception_handler

def custom_exception_handler(exc, context):
	# 调用REST framework默认的异常处理方法获得标准错误响应对象,None无异常,not None有错误
	response = exception_handler(exc, context)
	if response is not None:
		# 小范围异常错误捕捉
		logger.error(traceback.format_exc())
        error = ' '.join([str(i) for i in exc.args])
        data = {
            'code': status.HTTP_500_INTERNAL_SERVER_ERROR,
            'msg': '失败',
            'error': error,
            'payload': None,
            'status': 'error'
        }
        return Response(data, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
    if isinstance(exc, BaseException):  # 更大的异常错误范围捕捉
		# if isinstance(exc.detail, (list, dict)):
        #     if isinstance(exc.detail, (list,)):
        #         error = ' '.join([str(i) for i in exc.detail])
        #     else:
        #         error = ' '.join([str(i) for i in exc.detail.values()])
        logger.error(traceback.format_exc())
        error = ' '.join([str(i) for i in exc.args])

        set_rollback()
        data = {
            'code': status.HTTP_500_INTERNAL_SERVER_ERROR,
            'msg': '失败',
            'error': error,
            'payload': None,
            'status': 'error'
        }
        return Response(data, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
    return response  # 此时的response=None

二、python异常名汇总及关系

你可能感兴趣的:(web后端,python,代码,python,内置函数,Exception,错误捕捉,drf异常)