2016-03-27 67 views
0

我想從django-rest-auth中發現一個異常。類rest_auth.serializers.LoginSerializer拋出各種異常,所有exceptions.ValidationError如何在django-rest框架中獲得正確的驗證異常?

msg = _('Must include "email" and "password".') 
     raise exceptions.ValidationError(msg) 

msg = _('Must include "username" and "password".') 
     raise exceptions.ValidationError(msg) 

raise serializers.ValidationError(_('E-mail is not verified.')) 

我只在處理最後一個感興趣「電子郵件沒有被證實。」但try塊會捕獲所有ValidationError異常。鑑於字符串也被翻譯,我怎樣才能處理我感興趣的問題?這樣的支票會好嗎還是有更好的辦法?

if exc.data is _('E-mail is not verified.') 
    # do stuff 
    raise exc 

回答

1

基於驗證錯誤消息處理異常可能有點反模式,您可能會後悔那條道路。解決這個問題的一個方法是檢查引發異常的條件 - 在它出現異常之前。

我沒有關於你的應用程序的任何細節,但另一個選擇是覆蓋rest_auth序列化程序中的'validate'方法。這將允許您首先檢查條件(在rest_auth之前)並根據需要處理它。這個項目的好處是它們是開源的,你可以通過view the source來看看它是如何引發這個錯誤的。

class SpecialValidator(LoginSerializer): 
    def validate(self, attrs): 
     username = attrs.get('username') 
     email_address = user.emailaddress_set.get(email=user.email) 
     if not email_address.verified: 
      # This is where you put in your special handling 
     return super(SpecialValidator, self).validate(attrs) 
+0

謝謝你的回答。我曾考慮過對LoginSerializer類進行子分類並重寫validate方法。我主要關心的是驗證方法有許多代碼行,我不得不復制到我的覆蓋,並通過這樣做,我基本上會創建一個叉,不會從以後的改進中受益。但是你的建議似乎更簡單。 – voger