Drf错误定制

django框架 2020-04-22 797

有时候你可能希望在drf中抛出你希望的错误,而不是使用默认的错误配置,那有时非常难看,对于前端的调试也不够友好。比如下面这个:

上图中返回的错误虽然看起来是对的,但是对于前端来说,‘non_field_errors’字段显然不太适合来判断错误的类型,而更应该偏向于使用error_code来指代错误。(图中的status_code是修改后加上的)
drf提供了修改的方法:

def custom_exception_handler(exc, context):  
    """  
    error_code : 10001, 验证码验证出错  
    :param exc:  
    :param context:  
    :return:  
    """  
    # Call REST framework's default exception handler first,  
    # to get the standard error response.  
    response = exception_handler(exc, context)

    # Now add the HTTP status code to the response.  
    if response is not None:  
        response.data['status_code'] = response.status_code  
    return response  

还需要在setting.py中的REST_FRAMEWORK修改异常配置,改为:'EXCEPTION_HANDLER': 'user.customExection.custom_exception_handler'默认为'EXCEPTION_HANDLER': 'rest_framework.views.exception_handler'

标签:django框架

文章评论

评论列表

已有0条评论