2015-06-15 49 views

回答

2

內建的Python異常可能不適合你正在做的事情。您將希望子類基類Exception,並根據您想要溝通的每個方案拋出自己的自定義例外。

一個很好的例子是how the Python Requests HTTP library defines its own exceptions

In the event of a network problem (e.g. DNS failure, refused connection, etc), Requests will raise a ConnectionError exception.

In the rare event of an invalid HTTP response, Requests will raise an HTTPError exception.

If a request times out, a Timeout exception is raised.

If a request exceeds the configured number of maximum redirections, a TooManyRedirects exception is raised.

All exceptions that Requests explicitly raises inherit from requests.exceptions.RequestException .

3

你可以簡單地調用Response.raise_for_status()您的迴應:

>>> import requests 
>>> url = 'http://stackoverflow.com/doesnt-exist' 
>>> r = requests.get(url) 
>>> 
>>> print r.status_code 
404 
>>> r.raise_for_status() 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "requests/models.py", line 831, in raise_for_status 
    raise HTTPError(http_error_msg, response=self) 
requests.exceptions.HTTPError: 404 Client Error: Not Found 

這將提高一個requests.HTTPError任何4xx5xx響應。

有關更完整的示例,請參閱Response Status Code上的文檔。


注意這並你究竟問了什麼(status != 200):它不會引發異常的201 Created204 No Content,或任何3xx的重定向 - 但是這是最有可能你想要的行爲:requests只會跟隨重定向,而其他2xx通常只是在處理API時就好了。

相關問題