add error detail handling to DrBotzoBackend
written for expecting a JSON with detail in an error response, but might also decently handle the other cases
This commit is contained in:
parent
f048d7c193
commit
5e4bcf6b1c
|
@ -9,13 +9,36 @@ import hitomi.config as config
|
|||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class DrBotzoError(requests.HTTPError):
|
||||
"""Wrap HTTPError with the error detail from the dr.botzo API, if available."""
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
"""Initialize DrBotzoError."""
|
||||
detail = kwargs.pop('detail', None)
|
||||
self.detail = detail
|
||||
super(DrBotzoError, self).__init__(*args, **kwargs)
|
||||
|
||||
|
||||
class DrBotzoBackend(object):
|
||||
"""Basic HTTP requests API, wrapped with some authentication and config stuff."""
|
||||
|
||||
def post(self, url, **kwargs):
|
||||
"""Wrap requests.post with authentication and hostname settings."""
|
||||
return requests.post(urljoin(config.DR_BOTZO_BACKEND_HOST, url),
|
||||
auth=(config.DR_BOTZO_BACKEND_USER, config.DR_BOTZO_BACKEND_PASS), **kwargs)
|
||||
try:
|
||||
response = requests.post(urljoin(config.DR_BOTZO_BACKEND_HOST, url),
|
||||
auth=(config.DR_BOTZO_BACKEND_USER, config.DR_BOTZO_BACKEND_PASS), **kwargs)
|
||||
response.raise_for_status()
|
||||
return response
|
||||
except requests.ConnectionError as cex:
|
||||
logger.exception("received a connection error during POST %s", url)
|
||||
raise DrBotzoError(cex, detail="A connection error occurred.")
|
||||
except requests.HTTPError as httpex:
|
||||
logger.exception("received an HTTP error during POST %s", url)
|
||||
try:
|
||||
detail = httpex.response.json()['detail']
|
||||
raise DrBotzoError(httpex, detail=detail)
|
||||
except (ValueError, KeyError):
|
||||
raise DrBotzoError(httpex, detail="An unexpected error occurred.")
|
||||
|
||||
|
||||
dr_botzo = DrBotzoBackend()
|
||||
|
|
Loading…
Reference in New Issue