• drf自定义异常处理


    一、前言

    ​ 我们知道当前端传递到后端的数据不正确时,后端会将错误的信息返回到前端。如果我们后端服务器出现了异常,那就说明我们的后端逻辑出现了问题,需要对后端代码进行修改。

    ​ 我们需要在异常发生时,对异常进行捕获,并记录到日志文件当中,而不是将错误的信息直接返回到前端,这是没有意义的。那么我们如何来自定义自己的异常处理机制呢?

    二、drf默认异常处理

    rest_framework文件下的views.py中exception_handler方法

    def exception_handler(exc, context):
        if isinstance(exc, Http404):
            exc = exceptions.NotFound()
        elif isinstance(exc, PermissionDenied):
            exc = exceptions.PermissionDenied()
    
        if isinstance(exc, exceptions.APIException):
            headers = {}
            if getattr(exc, 'auth_header', None):
                headers['WWW-Authenticate'] = exc.auth_header
            if getattr(exc, 'wait', None):
                headers['Retry-After'] = '%d' % exc.wait
    
            if isinstance(exc.detail, (list, dict)):
                data = exc.detail
            else:
                data = {'detail': exc.detail}
    
            set_rollback()
            return Response(data, status=exc.status_code, headers=headers)
    	
        # 当exe不是APIException的实例时会返回None,导致了500错误。
        return None
    

    三、借用drf的异常处理来自定义

    exception.py
    from rest_framework.views import exception_handler
    from rest_framework.response import Response
    
    
    def my_exception_handler(exe, context):
        response = exception_handler(exe, context)
        if not response:
            # 此处对异常信息进行日志保存
            response = Response({'detail': '服务器异常,%s' % exe},status=500)
        return response
    

    四、修改配置文件

    settings.py
    REST_FRAMEWORK = {
        # 默认异常处理
        # 'EXCEPTION_HANDLER': 'rest_framework.views.exception_handler',
        
        'EXCEPTION_HANDLER': 'api.exception.my_exception_handler',
    }
    
  • 相关阅读:
    IIS: Idle Timeout vs Recycle
    Window.location
    Web technology for developersSee Web APIsStorage
    Know the basics about NTFS permissions
    设置描述性弹性域某个字段为只读
    adb root
    nvme WVLOCK
    模拟器获取root权限
    Android模拟器emulator基本使用技巧和命令
    人工智能可以产生自主意识吗
  • 原文地址:https://www.cnblogs.com/Ghostant/p/12363233.html
Copyright © 2020-2023  润新知