From 41a17d0566c6e6c5049e35f32e70d0ff1cad9ad5 Mon Sep 17 00:00:00 2001 From: "Dustin J. Mitchell" Date: Fri, 3 Jun 2016 14:25:21 -0500 Subject: [PATCH] Add client_resp.raise_for_status() (#908) This method raises an exception for statuses that represent an error. Closes #868. --- aiohttp/client_reqrep.py | 6 ++++++ docs/client_reference.rst | 5 +++++ tests/test_client_response.py | 13 +++++++++++++ 3 files changed, 24 insertions(+) diff --git a/aiohttp/client_reqrep.py b/aiohttp/client_reqrep.py index 656e31549c3..f2cc7c0fb5b 100644 --- a/aiohttp/client_reqrep.py +++ b/aiohttp/client_reqrep.py @@ -694,6 +694,12 @@ def release(self): self._connection = None self._cleanup_writer() + def raise_for_status(self): + if 400 <= self.status: + raise aiohttp.HttpProcessingError( + code=self.status, + message=self.reason) + def _cleanup_writer(self): if self._writer is not None and not self._writer.done(): self._writer.cancel() diff --git a/docs/client_reference.rst b/docs/client_reference.rst index 5262ffe2507..c303a994e14 100644 --- a/docs/client_reference.rst +++ b/docs/client_reference.rst @@ -1149,6 +1149,11 @@ Response object return it into free connection pool for re-usage by next upcoming request. + .. method:: raise_for_status() + + Raise an HttpProcessingError if the response status is 400 or higher. + Do nothing for success responses (less than 400). + .. comethod:: text(encoding=None) Read response's body and return decoded :class:`str` using diff --git a/tests/test_client_response.py b/tests/test_client_response.py index 7b578f50169..99458e8b6a5 100644 --- a/tests/test_client_response.py +++ b/tests/test_client_response.py @@ -274,3 +274,16 @@ def test_close_deprecated(self): with self.assertWarns(DeprecationWarning): self.response.close(force=False) self.assertIsNone(self.response._connection) + + def test_raise_for_status_2xx(self): + self.response.status = 200 + self.response.reason = 'OK' + self.response.raise_for_status() # should not raise + + def test_raise_for_status_4xx(self): + self.response.status = 409 + self.response.reason = 'CONFLICT' + with self.assertRaises(aiohttp.HttpProcessingError) as cm: + self.response.raise_for_status() + self.assertEqual(str(cm.exception.code), '409') + self.assertEqual(str(cm.exception.message), "CONFLICT")