Django rest framework 自定義Exception


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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM