zoukankan      html  css  js  c++  java
  • drf APIviews自定义异常处理

    drf APIviews自定义异常处理

    正常情况下APIview中的dispatch会帮我们处理部分异常,并返回response
    其他没有处理的异常就会报错,当我们不希望服务器返回错误页面时,就需要我们自己自定义异常处理
    
    
    
    from rest_framework.response import Response
    from rest_framework.views import exception_handler as drf_exception_handler  # drf提供的处理异常方法
    from rest_framework import status
    
    #自定义的异常处理方法
    def exception_handler(exc, context):
        exception = exc
        view = context.get('view')
        args = context.get('args')
        kwargs = context.get('kwargs')
        request = context.get('request')
    
        response = drf_exception_handler(exc, context)
    
        # drf没有提供处理的服务器异常
        if response is None:
            # 重点:有些异常信息需要记录日志文件
            # logging记录异常信息
            return Response('服务器错误', status=status.HTTP_500_INTERNAL_SERVER_ERROR)
    
        response.data = {
            'status': 1,
            'msg': response.data['detail']
        }
        return response
    
    
    # 在全局配置文件中更改处理异常的方法
    REST_FRAMEWORK = {
        # 异常句柄配置
        'EXCEPTION_HANDLER': 'api.exceptions.exception_handler',
    }
    
  • 相关阅读:
    前端之HTML补充
    前端之HTML
    mysql 视图,触发器,存储
    mysql 函数 事务
    索引扩展
    mysql数据库索引相关
    mysql 存储过程查询语句
    mysql 单表查询
    mysql 多表连接查询
    js引入的几种简单写法
  • 原文地址:https://www.cnblogs.com/zhouze/p/11385307.html
Copyright © 2011-2022 走看看