From: Tom Dyas Date: Mon, 23 Jun 2014 18:21:46 +0000 (-0400) Subject: http client: option to not raise errors X-Git-Tag: v4.1.0b1~51^2 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=refs%2Fpull%2F1258%2Fhead;p=thirdparty%2Ftornado.git http client: option to not raise errors Pass raise_error=False to the fetch method to disable the raising of HTTPError on errors. --- diff --git a/tornado/httpclient.py b/tornado/httpclient.py index df4295171..6ea872de2 100644 --- a/tornado/httpclient.py +++ b/tornado/httpclient.py @@ -95,7 +95,8 @@ class HTTPClient(object): If it is a string, we construct an `HTTPRequest` using any additional kwargs: ``HTTPRequest(request, **kwargs)`` - If an error occurs during the fetch, we raise an `HTTPError`. + If an error occurs during the fetch, we raise an `HTTPError` unless + the ``raise_error`` keyword argument is set to False. """ response = self._io_loop.run_sync(functools.partial( self._async_client.fetch, request, **kwargs)) @@ -200,7 +201,7 @@ class AsyncHTTPClient(Configurable): raise RuntimeError("inconsistent AsyncHTTPClient cache") del self._instance_cache[self.io_loop] - def fetch(self, request, callback=None, **kwargs): + def fetch(self, request, callback=None, raise_error=True, **kwargs): """Executes a request, asynchronously returning an `HTTPResponse`. The request may be either a string URL or an `HTTPRequest` object. @@ -208,8 +209,10 @@ class AsyncHTTPClient(Configurable): kwargs: ``HTTPRequest(request, **kwargs)`` This method returns a `.Future` whose result is an - `HTTPResponse`. The ``Future`` will raise an `HTTPError` if - the request returned a non-200 response code. + `HTTPResponse`. By default, the ``Future`` will raise an `HTTPError` + if the request returned a non-200 response code. Instead, if + ``raise_error`` is set to False, the response will always be + returned regardless of the response code. If a ``callback`` is given, it will be invoked with the `HTTPResponse`. In the callback interface, `HTTPError` is not automatically raised. @@ -243,7 +246,7 @@ class AsyncHTTPClient(Configurable): future.add_done_callback(handle_future) def handle_response(response): - if response.error: + if raise_error and response.error: future.set_exception(response.error) else: future.set_result(response) diff --git a/tornado/test/httpclient_test.py b/tornado/test/httpclient_test.py index bfb50d878..b155c6eeb 100644 --- a/tornado/test/httpclient_test.py +++ b/tornado/test/httpclient_test.py @@ -404,6 +404,11 @@ Transfer-Encoding: chunked self.assertEqual(context.exception.code, 404) self.assertEqual(context.exception.response.code, 404) + @gen_test + def test_future_http_error_no_raise(self): + response = yield self.http_client.fetch(self.get_url('/notfound'), raise_error=False) + self.assertEqual(response.code, 404) + @gen_test def test_reuse_request_from_response(self): # The response.request attribute should be an HTTPRequest, not