赞
踩
REST framework提供了异常处理,我们可以自定义异常处理函数。
- from rest_framework.views import exception_handler
-
- def custom_exception_handler(exc, context):
- # 先调用REST framework默认的异常处理方法获得标准错误响应对象
- response = exception_handler(exc, context)
-
- # 在此处补充自定义的异常处理
- if response is not None:
- response.data['status_code'] = response.status_code
-
- return response
在配置文件中声明自定义的异常处理
- REST_FRAMEWORK = {
- 'EXCEPTION_HANDLER': 'my_project.my_app.utils.custom_exception_handler'
- }
如果未声明,会采用默认的方式,如下
- REST_FRAMEWORK = {
- 'EXCEPTION_HANDLER': 'rest_framework.views.exception_handler'
- }
例如:
补充上处理关于数据库的异常
- from rest_framework.views import exception_handler as drf_exception_handler
- from rest_framework import status
- from django.db import DatabaseError
-
- def exception_handler(exc, context):
- response = drf_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
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。