voger
voger

Reputation: 676

How to get the right Validation exception in django-rest framework?

I want to catch an exception from django-rest-auth. The class rest_auth.serializers.LoginSerializer throws various exceptions, all exceptions.ValidationError

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.'))

I am only interested in handling the last one 'E-mail is not verified.' but a try block will catch all ValidationError exceptions. How can I handle only the one that interests me given that the string is also translated? would a check like this be ok or there is a better way?

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

Upvotes: 0

Views: 768

Answers (1)

Tristan
Tristan

Reputation: 141

Handling exceptions based on the Validation Error message might be a bit of an anti-pattern, and you might regret going down that road. One way around this is to check the conditions that raise the exceptions - before it becomes in an exception.

I don't have any details of your app, but another option would be to override the 'validate' method in rest_auth serializer. This would allow you to check the for the condition first (before rest_auth) and handle it however you want. The nice thing about this projects is that they are open source, and you can view the source to see how it raises this error.

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)

Upvotes: 1

Related Questions