问题
I have a function in a Manager which activates a user account via a key. When a key is provided, several checks need to be performed: does the key exist? has the key expired? and then if not, the manager activates the account.
def activate(key):
try:
profile = self.get(key=key)
except self.model.DoesNotExist:
return None
if not profile.key_expired():
## Activate user
return user
return None
The issue is of course, that this returns False for both 'the key doesn't exist', and 'the key given is expired'. Giving False for both doesn't tell my upstream view what was the issue at hand. I don't do a 404 error as that is opaque to the user and doesn't help matters.
What is the best/correct django/pythonic way of handling this to give more useful information upstream? Are custom errors the way forward? Should I return values for analysis upstream (seems an ugly solution)? Is there another way?
回答1:
I'd raise an exception inside activate and catch it outside.
def activate(key):
try:
profile = self.get_query_set().get(key=key)
except self.model.DoesNotExist:
raise
if profile.key_expired():
raise YourCustomException()
# or simply return False
## Activate user
return user
Also I'd suggest to use self.get_query_set().get(key=key)
instead of self.get(key=key)
来源:https://stackoverflow.com/questions/9181493/django-exceptions-and-returns-what-is-the-correct-way-to-handle-multiple-poten