2015-06-15 53 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时就好了。

相关问题