async def generate_error_response( response: aiohttp.ClientResponse) -> errors.HTTPError: """Given an erroneous HTTP response, return a corresponding exception.""" real_url = str(response.real_url) raw_body = await response.read() # Little hack to stop mypy from complaining when using `*args` args: typing.List[typing.Any] = [real_url, response.headers, raw_body] try: json_body = await response.json() args.append(json_body.get("message", "")) args.append(errors.RESTErrorCode(json_body.get("code", 0))) except aiohttp.ContentTypeError: pass if response.status == http.HTTPStatus.BAD_REQUEST: return errors.BadRequestError(*args) if response.status == http.HTTPStatus.UNAUTHORIZED: return errors.UnauthorizedError(*args) if response.status == http.HTTPStatus.FORBIDDEN: return errors.ForbiddenError(*args) if response.status == http.HTTPStatus.NOT_FOUND: return errors.NotFoundError(*args) status = http.HTTPStatus(response.status) if 400 <= status < 500: return errors.ClientHTTPResponseError(real_url, status, response.headers, raw_body) elif 500 <= status < 600: return errors.InternalServerError(real_url, status, response.headers, raw_body) else: return errors.HTTPResponseError(real_url, status, response.headers, raw_body)
def error(self): return errors.HTTPResponseError( "https://some.url", http.HTTPStatus.BAD_REQUEST, {}, "raw body", "message", 12345, )