https://github.com/Coxhuang/django-execptions
Python3.6
Django==2.0.7
djangorestframework==3.8.2
{
"detail": "Method \"PUT\" not allowed."
}
改成
{
"msg": "Method \"PUT\" not allowed."
}
新建文件(这里命名为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
REST_FRAMEWORK = {
...
'EXCEPTION_HANDLER': 'app.execption.custom_exception_handler', # 指定刚刚新建的execption.py文件
}
系统异常
{
"name": [
"This field is required."
],
"age": [
"This field is required."
]
}
改后
{
"code": "422",
"message": "Validation Failed",
"errors": [
{
"field": "name",
"message": "This field is required."
},
{
"field": "age",
"message": "This field is required."
}
]
}