Browse Source

Properly catch non-JSON response errors

Tulir Asokan 3 years ago
parent
commit
87d00dbb57
3 changed files with 18 additions and 2 deletions
  1. 1 0
      mauigpapi/errors/__init__.py
  2. 11 0
      mauigpapi/errors/response.py
  3. 6 2
      mauigpapi/http/base.py

+ 1 - 0
mauigpapi/errors/__init__.py

@@ -19,6 +19,7 @@ from .response import (
     IGRateLimitError,
     IGResponseError,
     IGSentryBlockError,
+    IGUnknownError,
     IGUserHasLoggedOutError,
 )
 from .state import IGCookieNotFoundError, IGNoCheckpointError, IGUserIDNotFoundError

+ 11 - 0
mauigpapi/errors/response.py

@@ -33,6 +33,17 @@ class IGChallengeWrongCodeError(IGError):
     pass
 
 
+class IGUnknownError(IGError):
+    response: ClientResponse
+
+    def __init__(self, response: ClientResponse) -> None:
+        super().__init__(
+            f"Request {response.request_info.method} {response.request_info.url.path} failed: "
+            f"HTTP {response.status} with non-JSON body"
+        )
+        self.response = response
+
+
 class IGResponseError(IGError):
     response: ClientResponse
 

+ 6 - 2
mauigpapi/http/base.py

@@ -21,7 +21,7 @@ import logging
 import random
 import time
 
-from aiohttp import ClientResponse, ClientSession
+from aiohttp import ClientResponse, ClientSession, ContentTypeError
 from yarl import URL
 
 from mautrix.types import JSON, Serializable
@@ -43,6 +43,7 @@ from ..errors import (
     IGRateLimitError,
     IGResponseError,
     IGSentryBlockError,
+    IGUnknownError,
     IGUserHasLoggedOutError,
 )
 from ..state import AndroidState
@@ -176,7 +177,10 @@ class BaseAndroidAPI:
 
     async def _handle_response(self, resp: ClientResponse) -> JSON:
         self._handle_response_headers(resp)
-        body = await resp.json()
+        try:
+            body = await resp.json()
+        except (json.JSONDecodeError, ContentTypeError) as e:
+            raise IGUnknownError(resp) from e
         if body.get("status", "fail") == "ok":
             return body
         else: