Skip to content

Commit

Permalink
Add handling for exceptions raised by requests library
Browse files Browse the repository at this point in the history
Signed-off-by: Adam Beckmeyer <adam_git@thebeckmeyers.xyz>
  • Loading branch information
non-Jedi committed Oct 24, 2017
1 parent 3039e32 commit 99aa557
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 8 deletions.
21 changes: 13 additions & 8 deletions matrix_client/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
import json
import requests
from time import time, sleep
from .errors import MatrixError, MatrixRequestError
from .errors import MatrixError, MatrixRequestError, MatrixHttpLibError

try:
from urllib import quote
Expand Down Expand Up @@ -585,13 +585,18 @@ def _send(self, method, path, content=None, query_params={}, headers={},

response = None
while True:
response = requests.request(
method, endpoint,
params=query_params,
data=content,
headers=headers,
verify=self.validate_cert
)
try:
response = requests.request(
method, endpoint,
params=query_params,
data=content,
headers=headers,
verify=self.validate_cert
)
except requests.exceptions.RequestException as e:
raise MatrixHttpLibError(
"Something went wrong in sending the request", e
)

if response.status_code == 429:
sleep(response.json()['retry_after_ms'] / 1000)
Expand Down
9 changes: 9 additions & 0 deletions matrix_client/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ class MatrixError(Exception):

class MatrixUnexpectedResponse(MatrixError):
"""The home server gave an unexpected response. """

def __init__(self, content=""):
super(MatrixError, self).__init__(content)
self.content = content
Expand All @@ -17,3 +18,11 @@ def __init__(self, code=0, content=""):
super(MatrixRequestError, self).__init__("%d: %s" % (code, content))
self.code = code
self.content = content


class MatrixHttpLibError(MatrixError):
"""The library used for http requests raised an exception."""

def __init__(self, msg, original_exception):
super(MatrixHttpLibError, self).__init__(msg + ": {}".format(original_exception))
self.original_exception = original_exception

0 comments on commit 99aa557

Please sign in to comment.