使用条件返回重构代码

时间:2014-08-12 15:55:25

标签: python

我在多个函数的开头就有我的项目代码。

try: 
    user = get_user(user_id) 
except LockedException: 
    logger.warn('op=healthcheck, msg="user is locked"') 
    return HttpResponseServerError(jsonMessage('user=%(user)s is locked' % {'user': user_id})) 
except UserFreeException: 
    logger.warn('op=user, msg="user is free"') 
    return HttpResponseNotFound(jsonMessage('user is free user=%(user)s' % {'user': user_id})) 
except User.DoesNotExist: 
    logger.warn('op=healthcheck, msg="user doesn\'t exist"') 
    return HttpResponseNotFound(jsonMessage('invalid user=%(user)s' % {'user': user_id})) 
except Exception, e: 
    logger.error('op=healthcheck, msg="unknown error", msg="%(exception)s"', 
                 {'exception': e.message}) 
    return HttpResponseServerError(jsonMessage(e.message)) 

有关如何重构它的任何提示,以便我不需要在任何地方重复使用它? 我能得到的最好的方法是创建一个函数,在出现问题时抛出一个异常,这个异常包含一个" http_response"字段,所以我做了类似的事情:

try:
    user = get_user(user_id)
except MyGenericException, e:
    return e.http_response

还有其他想法吗?

1 个答案:

答案 0 :(得分:1)

更新了@ steveha的建议

如何在函数中使用它:

def safe_get_user(user_id):
    user = error_response = None
    try: 
        user = get_user(user_id) 
    except LockedException: 
        logger.warn('op=healthcheck, msg="user is locked"') 
        error_response = HttpResponseServerError(jsonMessage('user=%(user)s is locked' % {'user': user_id})) 
    except UserFreeException: 
        logger.warn('op=user, msg="user is free"') 
        error_response = HttpResponseNotFound(jsonMessage('user is free user=%(user)s' % {'user': user_id})) 
    except User.DoesNotExist: 
        logger.warn('op=healthcheck, msg="user doesn\'t exist"') 
        error_response = HttpResponseNotFound(jsonMessage('invalid user=%(user)s' % {'user': user_id})) 
    except Exception, e: 
        logger.error('op=healthcheck, msg="unknown error", msg="%(exception)s"', 
             {'exception': e.message}) 
        error_response = HttpResponseServerError(jsonMessage(e.message))
    return user, error_response

然后,在你想要执行它的任何地方:

user, error_response = safe_get_user(user_id)
if error_response is not None:
    return error_response