Django 解決開發(fā)自定義拋出異常的問題
在開發(fā)過程中,針對(duì)用戶輸入的不合法信息,我們應(yīng)該在后端進(jìn)行數(shù)據(jù)驗(yàn)證,并拋出相關(guān)的異常傳遞到前端來提示用戶。
可是如何進(jìn)行自定義拋出異常信息呢?通常處理方法有三種,我將依次介紹這三種方法。
第一種方法:
這種方法最為簡單,只需要?jiǎng)?chuàng)建一個(gè)字典對(duì)象,通過render傳到前端即可。
字典對(duì)象如下:
result = {’code’:’’, ’message’:’’}render(request, ’xxx.html’, result:result)
第二種方法:
需要繼承Exception類, 代碼如下:
# 利用繼承自定義異常提示信息class MyException(Exception): def __init__(self, code, error, data): self.code = code self.error = error self.data = datatry: if not 1 < 0: raise MyException(1001, ’你的說法錯(cuò)誤’, ’1不小于0’)except MyException as e: pass
第三種方法:
自定義一個(gè)繼承 object 的類
class MyTest(object): def __init__(self): # 自定義狀態(tài)碼 self.code = 1000 self.error = ’’ self.data = ’’ @property def dict(self): return self.__dict__
在你需要自定義異常的時(shí)候,創(chuàng)建一個(gè)對(duì)象,并制定相關(guān)信息。
# 創(chuàng)建實(shí)例對(duì)象one = MyTest()one.code = 1001one.error = ’你錯(cuò)了’one.data = ’請(qǐng)?jiān)俅螜z查’ print(one.dict)
綜上所述是筆者常用來在后端檢驗(yàn)數(shù)據(jù)并拋出相關(guān)異常信息的三種方法。
補(bǔ)充知識(shí):Django rest framework 自定義異常處理
1.
在settings.py中需要添加的配置
1.install app中添加 ’rest_framework’,
2.在settings中的 添加這個(gè)配置
REST_FRAMEWORK = { ’EXCEPTION_HANDLER’:’common.restframework.xd_exceptions.custom_exception_handler’, #這是使用自定制異常處理}
xd_exceptions.py這里是異常處理函數(shù)
from rest_framework.views import exception_handlerdef custom_exception_handler(exc, context): # Call REST framework’s default exception handler first, # to get the standard error response. response = exception_handler(exc, context) # Now add the HTTP status code to the response. if response is not None: response.data[’status_code’] = response.status_code print(response.data) # response.data[’message’] =response.data[’detail’] #增加message這個(gè)key # response.data[’message’] =’方法不對(duì)’ #增加message這個(gè)key return response
自定義異常類 在主動(dòng)拋出異常的時(shí)候就可以拋出一個(gè)下邊類型的異常
my_errors.py
from rest_framework import statusfrom rest_framework.exceptions import APIExceptionfrom common.tools import xd_status# class ParseError(APIException):# status_code = xd_status.HTTP_400_BAD_REQUEST# default_detail = ’這是.default_detail========’# default_code = ’parse_error’#class XdError(APIException): passclass ParamError(XdError): status_code = 400class Unauthorized(XdError): status_code = 401class PermissionDenied(XdError): status_code = 403class ObjectNotFound(XdError): status_code = 404class ServerError(XdError): status_code = 500class ErrorCode: UNAUTHORIZED = 10000 # 未登錄 PERMISSION_DENIED = 10001 # 無權(quán)限 PARAM_ERROR = 40000 # 參數(shù)驗(yàn)證錯(cuò)誤 DATA_NOT_FOUND = 40001 # 未找到數(shù)據(jù) DATA_NOT_VALID = 40002 # 數(shù)據(jù)錯(cuò)誤 REPEAT_POST = 40003 # 重復(fù)提交 EEEE = 40003 # 新型錯(cuò)誤
在視圖或函數(shù)中主動(dòng)拋出異常,
class SupserUserDetailView(APIView): # authentication_classes = [] permission_classes = [SupserPermisson,] def put(self,request,pk): if not request.user.is_superuser: if request.user.id != pk:raise ParamError(’用戶沒有修改權(quán)限’, ErrorCode.EEEE) #這就是拋出自定義異常, 然后自己的異常捕獲方式就能捕獲這個(gè)異常 user = User.objects.filter(id=pk) if not user: raise ParamError(’被修改的用戶不存在’, ErrorCode.EEEE) data = handel_c_user(request.data) user_obj = Creat_newuser_serializers(data=data, instance=user.first()) if user_obj.is_valid(): user_obj.save() res={’status’:'修改成功'} return JsonResponse(data=res, code=200, desc='success', status=status.HTTP_200_OK) res = {’status’:user_obj.errors} return JsonResponse(data=res,code=200,desc='success',status=status.HTTP_200_OK)
工作流程
訪問觸發(fā)異常
自動(dòng)拋出自定制異常
自定義異常捕獲函數(shù)捕獲到異常并將用戶友好的數(shù)據(jù)返回給前端
以上這篇Django 解決開發(fā)自定義拋出異常的問題就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. PHP正則表達(dá)式函數(shù)preg_replace用法實(shí)例分析2. 一個(gè) 2 年 Android 開發(fā)者的 18 條忠告3. vue使用moment如何將時(shí)間戳轉(zhuǎn)為標(biāo)準(zhǔn)日期時(shí)間格式4. js select支持手動(dòng)輸入功能實(shí)現(xiàn)代碼5. Android 實(shí)現(xiàn)徹底退出自己APP 并殺掉所有相關(guān)的進(jìn)程6. Android studio 解決logcat無過濾工具欄的操作7. 什么是Python變量作用域8. vue-drag-chart 拖動(dòng)/縮放圖表組件的實(shí)例代碼9. Spring的異常重試框架Spring Retry簡單配置操作10. Vue實(shí)現(xiàn)仿iPhone懸浮球的示例代碼
