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 abb8b10 commit 48efa5b
Showing 1 changed file with 15 additions and 1 deletion.
16 changes: 15 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, Dict, Mapping, Optional, Union

from requests import Response
from requests.exceptions import JSONDecodeError


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

def __init__(self, response: Response):
super().__init__(self._extract_error(response))
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] = response.json()["error"]
self.code: int = self.error["code"]
Expand Down

0 comments on commit 48efa5b

Please sign in to comment.