Django RESTFramework 自定义异常Execptions
django REST Framework中的系统异常抛出的信息是detail:“xxxx”,需要把detail改...
扫描右侧二维码阅读全文
05
2021/11

Django RESTFramework 自定义异常Execptions

django REST Framework中的系统异常抛出的信息是detail:“xxxx”,需要把detail改成统一的"msg"
系统抛出的异常,改成我们想要的格式

REST_FRAMEWORK = {
    ...
    'EXCEPTION_HANDLER': 'app.execption.custom_exception_handler', # 指定刚刚新建的execption.py文件 
}

execption.py

from rest_framework.views import exception_handler
from rest_framework.exceptions import APIException
from rest_framework import status

def custom_exception_handler(exc,context):
    response = exception_handler(exc,context) #获取本来应该返回的exception的response
    if response is not None:
        try:
            response.data["msg"] = response.data['detail'] #改这里
            del response.data['detail']
        except:pass
    return response
Last modification:November 5th, 2021 at 02:28 pm
If you think my article is useful to you, please feel free to appreciate

Leave a Comment