本文主要是介绍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_handlerdef 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_handlerdef 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异常名汇总及关系
这篇关于restframework的异常处理的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!