| 106 | |
| 107 | |
| 108 | def handle_http_response(response: requests.Response, |
| 109 | logger, |
| 110 | cookies, |
| 111 | model_id, |
| 112 | raise_on_error: Optional[bool] = True) -> int: |
| 113 | http_error_msg = '' |
| 114 | if isinstance(response.reason, bytes): |
| 115 | try: |
| 116 | reason = response.reason.decode('utf-8') |
| 117 | except UnicodeDecodeError: |
| 118 | reason = response.reason.decode('iso-8859-1') |
| 119 | else: |
| 120 | reason = response.reason |
| 121 | request_id = get_request_id(response) |
| 122 | |
| 123 | # Try to extract server-side error detail from JSON response body. |
| 124 | server_message = '' |
| 125 | if response.status_code >= 400: |
| 126 | try: |
| 127 | resp_json = response.json() |
| 128 | # OpenAPI envelope: {"success": false, "code": "...", "message": "..."} |
| 129 | msg = resp_json.get('message') or resp_json.get('Message') or '' |
| 130 | code = resp_json.get('code') or '' |
| 131 | if msg: |
| 132 | server_message = f' | Server message: [{code}] {msg}' if code else f' | Server message: {msg}' |
| 133 | except (ValueError, AttributeError): |
| 134 | # Not JSON or unexpected structure; try raw text (truncated) |
| 135 | body_text = response.text[:500] if response.text else '' |
| 136 | if body_text: |
| 137 | server_message = f' | Response body: {body_text}' |
| 138 | |
| 139 | if 404 == response.status_code: |
| 140 | http_error_msg = ( |
| 141 | u'404 Not Found: %s does not exist or is not accessible, ' |
| 142 | u'Request id: %s for url: %s%s' % |
| 143 | (model_id, request_id, response.url, server_message)) |
| 144 | elif 403 == response.status_code: |
| 145 | if cookies is None: |
| 146 | http_error_msg = ( |
| 147 | f'Authentication token does not exist, failed to access {model_id} ' |
| 148 | f'which may not exist or may be private. Please login first.{server_message}' |
| 149 | ) |
| 150 | |
| 151 | else: |
| 152 | http_error_msg = ( |
| 153 | f'The authentication token is invalid, failed to access {model_id}.{server_message}' |
| 154 | ) |
| 155 | elif 400 <= response.status_code < 500: |
| 156 | http_error_msg = u'%s Client Error: %s, Request id: %s for url: %s%s' % ( |
| 157 | response.status_code, reason, request_id, response.url, |
| 158 | server_message) |
| 159 | |
| 160 | elif 500 <= response.status_code < 600: |
| 161 | http_error_msg = u'%s Server Error: %s, Request id: %s, for url: %s%s' % ( |
| 162 | response.status_code, reason, request_id, response.url, |
| 163 | server_message) |
| 164 | if http_error_msg and raise_on_error: # there is error. |
| 165 | logger.error(http_error_msg) |