使用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')即可。