2015-06-22 101 views
3

我正在使用Python 2.7,並且是自定義異常的新增功能。我儘可能多地閱讀了他們,但對於這個特殊問題找不到什麼幫助。Python條件異常消息

我打電話給一個API返回一個狀態代碼與大多數答覆。例如,0是'成功',1是'參數數量錯誤',2是'缺少參數'等。

當我收到響應時,檢查狀態以確保不會繼續有些事情是錯的。我一直提出一個通用的異常,例如:

if response.get('status') != 0: 
    print 'Error: Server returned status code %s' % response.get('status') 
    raise Exception 

如何創建一個自定義異常中查找狀態代碼是什麼,並將它作爲異常的錯誤消息的一部分?我設想是這樣的:

if response.get('status') != 0: 
    raise myException(response.get('status')) 

回答

2

所以,你可以通過自定義一個異常類子類Exception

例子:

class APIError(Exception): 
    """An API Error Exception""" 

    def __init__(self, status): 
     self.status = status 

    def __str__(self): 
     return "APIError: status={}".format(self.status) 


if response.get('status') != 0: 
    raise APIError(response.get('status')) 

通過子類標準Exception類所有默認/內置的異常繼承自您,也可以很容易地捕捉到您的自定義異常:

try: 
    # ... 
except APIError as error: 
    # ... 

參見:User-defined Exceptions

1

聲明一個自定義異常就像聲明一個普通班。做這樣的事情:

class MyException(Exception): 
    pass 

if response.get('status') != 0: 
    raise MyException(response.get('status')) 

所以如果response.get('status')的結果是1,你會得到MyException: Wrong Number of Parameters

另一個較短的版本可以工作,但它不會讓你自己命名異常。

if response.get('status') != 0: 
    raise Exception(response.get('status')) 

由於Exception是內建的Python類,因此會引發錯誤。再次,如果response.get('status')是1,您將得到Exception: Wrong Number of Parameters

+0

@JamesMills編輯。很糟糕的工作。謝謝 – michaelpri