当前位置:   article > 正文

异常处理 Exceptions

异常处理 Exceptions

异常处理 Exceptions

REST framework提供了异常处理,我们可以自定义异常处理函数。

  1. from rest_framework.views import exception_handler
  2. def custom_exception_handler(exc, context):
  3. # 先调用REST framework默认的异常处理方法获得标准错误响应对象
  4. response = exception_handler(exc, context)
  5. # 在此处补充自定义的异常处理
  6. if response is not None:
  7. response.data['status_code'] = response.status_code
  8. return response

在配置文件中声明自定义的异常处理

  1. REST_FRAMEWORK = {
  2. 'EXCEPTION_HANDLER': 'my_project.my_app.utils.custom_exception_handler'
  3. }

如果未声明,会采用默认的方式,如下

  1. REST_FRAMEWORK = {
  2. 'EXCEPTION_HANDLER': 'rest_framework.views.exception_handler'
  3. }

例如:

补充上处理关于数据库的异常

  1. from rest_framework.views import exception_handler as drf_exception_handler
  2. from rest_framework import status
  3. from django.db import DatabaseError
  4. def exception_handler(exc, context):
  5. response = drf_exception_handler(exc, context)
  6. if response is None:
  7. view = context['view']
  8. if isinstance(exc, DatabaseError):
  9. print('[%s]: %s' % (view, exc))
  10. response = Response({'detail': '服务器内部错误'}, status=status.HTTP_507_INSUFFICIENT_STORAGE)
  11. return response

REST framework定义的异常

  • APIException 所有异常的父类
  • ParseError 解析错误
  • AuthenticationFailed 认证失败
  • NotAuthenticated 尚未认证
  • PermissionDenied 权限决绝
  • NotFound 未找到
  • MethodNotAllowed 请求方式不支持
  • NotAcceptable 要获取的数据格式不支持
  • Throttled 超过限流次数
  • ValidationError 校验失败
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/爱喝兽奶帝天荒/article/detail/979472
推荐阅读
相关标签
  

闽ICP备14008679号