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.

extract the returned text so if we any bit of valid information at least
we can pass that to the application.

This could be helpfull to if we add calls to the API made for web
browser that returns HTML error message, it will fail to decode the
recieved error and raise a proper error.

closes #1504

Signed-off-by: Alexandre Lavigne <[email protected]>
(cherry picked from commit db59084)
  • Loading branch information
lavigne958 authored and alifeee committed Oct 3, 2024
1 parent a3e1ccd commit 9917d07
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": response.text,
"status": "invalid JSON",
}

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

0 comments on commit 9917d07

Please sign in to comment.