HTTP data was invalid or unexpected.
| 33 | |
| 34 | |
| 35 | class HttpError(Error): |
| 36 | """HTTP data was invalid or unexpected.""" |
| 37 | |
| 38 | @util.positional(3) |
| 39 | def __init__(self, resp, content, uri=None): |
| 40 | self.resp = resp |
| 41 | if not isinstance(content, bytes): |
| 42 | raise TypeError("HTTP content should be bytes") |
| 43 | self.content = content |
| 44 | self.uri = uri |
| 45 | self.error_details = "" |
| 46 | self.reason = self._get_reason() |
| 47 | |
| 48 | @property |
| 49 | def status_code(self): |
| 50 | """Return the HTTP status code from the response content.""" |
| 51 | return self.resp.status |
| 52 | |
| 53 | def _get_reason(self): |
| 54 | """Calculate the reason for the error from the response content.""" |
| 55 | reason = self.resp.reason |
| 56 | try: |
| 57 | try: |
| 58 | data = json.loads(self.content.decode("utf-8")) |
| 59 | except json.JSONDecodeError: |
| 60 | # In case it is not json |
| 61 | data = self.content.decode("utf-8") |
| 62 | if isinstance(data, dict): |
| 63 | reason = data["error"]["message"] |
| 64 | error_detail_keyword = next( |
| 65 | ( |
| 66 | kw |
| 67 | for kw in ["detail", "details", "errors", "message"] |
| 68 | if kw in data["error"] |
| 69 | ), |
| 70 | "", |
| 71 | ) |
| 72 | if error_detail_keyword: |
| 73 | self.error_details = data["error"][error_detail_keyword] |
| 74 | elif isinstance(data, list) and len(data) > 0: |
| 75 | first_error = data[0] |
| 76 | reason = first_error["error"]["message"] |
| 77 | if "details" in first_error["error"]: |
| 78 | self.error_details = first_error["error"]["details"] |
| 79 | else: |
| 80 | self.error_details = data |
| 81 | except (ValueError, KeyError, TypeError): |
| 82 | pass |
| 83 | if reason is None: |
| 84 | reason = "" |
| 85 | return reason.strip() |
| 86 | |
| 87 | def __repr__(self): |
| 88 | if self.error_details: |
| 89 | return '<HttpError %s when requesting %s returned "%s". Details: "%s">' % ( |
| 90 | self.resp.status, |
| 91 | self.uri, |
| 92 | self.reason, |
no outgoing calls
searching dependent graphs…