使用Dango rest framework时,有时需要raise APIException到前端,为了统一错误返回格式,我们需要对exception的格式进行调整。

方法:

1. 在project/utils目录下新建exceptions.py

内容:  

 1 from rest_framework.views import exception_handler
 2 
 3 
 4 def custom_exception_handler(exc,context):
 9     response = exception_handler(exc,context) #获取本来应该返回的exception的response 
11     if response is not None:
12         #response.data['status_code'] = response.status_code  #可添加status_code
13         response.data['message'] = response.data['detail']    #增加message这个key
15         del response.data['detail']  #删掉原来的detail
16 17 return response

2. 在project/project/settings.py中,增加如下高亮设置:

 1 REST_FRAMEWORK = {
 2 # Use Django's standard `django.contrib.auth` permissions,
 3 # or allow read-only access for unauthenticated users.
 4 'DEFAULT_PERMISSION_CLASSES': [
 5     'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly',
 8 ],
10 'DEFAULT_THROTTLE_CLASSES': (
11         'rest_framework.throttling.AnonRateThrottle',
12     ),
13 'DEFAULT_THROTTLE_RATES': {
14         'anon': '2/second',
15     },
16 'EXCEPTION_HANDLER': 'utils.exceptions.custom_exception_handler'
17 
18 }

3. 在app/views.py中,正常使用raise APIException('lalalalal')即可。