Skip to content

Commit

Permalink
better handler API error parsing.
Browse files Browse the repository at this point in the history
Possibly we encountered an error while parsing the API error JSON, like
connection closes early etc and the received JSON is invalid.

Better handle such scenario and build a valid error Dict to keep the
exception stack flow running and raise this message to the application.

Signed-off-by: Alexandre Lavigne <[email protected]>
  • Loading branch information
lavigne958 committed Sep 8, 2024
1 parent c76ad22 commit 22b5456
Showing 1 changed file with 14 additions and 1 deletion.
15 changes: 14 additions & 1 deletion gspread/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
from typing import Any, Mapping

from requests import Response
from requests.exceptions import JSONDecodeError


class UnSupportedExportFormat(Exception):
Expand Down Expand Up @@ -40,7 +41,19 @@ class APIError(GSpreadException):
such as when we attempt to retrieve things that don't exist."""

def __init__(self, response: Response):
error = dict(response.json()["error"])
try:
error = response.json()["error"]
except JSONDecodeError:
# in case we failed to parse the error from the API
# build an empty error object to notify the caller
# and keep the exception raise flow running

error = {
"code": -1,
"message": "failed to parse API error",
"status": "invalid JSON",
}

super().__init__(error)
self.response: Response = response
self.error: Mapping[str, Any] = error
Expand Down

0 comments on commit 22b5456

Please sign in to comment.