diff --git a/aiohttp/client_reqrep.py b/aiohttp/client_reqrep.py index a4c872ea1a6..80fdc7e02ee 100644 --- a/aiohttp/client_reqrep.py +++ b/aiohttp/client_reqrep.py @@ -691,6 +691,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 6c1de527535..e9efa073d43 100644 --- a/docs/client_reference.rst +++ b/docs/client_reference.rst @@ -1147,6 +1147,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")