Django: exceptions and returns, what is the correct way to handle multiple potential situations?

霸气de小男生 提交于 2019-12-13 19:17:36

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!