Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove passing exception as args to super in APIError #1477

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 7 additions & 12 deletions gspread/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

"""

from typing import Any, Dict, Mapping, Optional, Union
from typing import Any, Mapping

from requests import Response

Expand Down Expand Up @@ -40,20 +40,12 @@ 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))
error = dict(response.json()["error"])
super().__init__(error)
self.response: Response = response
self.error: Mapping[str, Any] = response.json()["error"]
self.error: Mapping[str, Any] = error
self.code: int = self.error["code"]

def _extract_error(
self, response: Response
) -> Optional[Dict[str, Union[int, str]]]:
try:
errors = response.json()
return dict(errors["error"])
except (AttributeError, KeyError, ValueError):
return None

def __str__(self) -> str:
return "{}: [{}]: {}".format(
self.__class__.__name__, self.code, self.error["message"]
Expand All @@ -62,6 +54,9 @@ def __str__(self) -> str:
def __repr__(self) -> str:
return self.__str__()

def __reduce__(self) -> tuple:
return self.__class__, (self.response,)


class SpreadsheetNotFound(GSpreadException):
"""Trying to open non-existent or inaccessible spreadsheet."""
9 changes: 8 additions & 1 deletion tests/worksheet_test.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import itertools
import pickle # nosec
import random
import re
from inspect import signature
Expand Down Expand Up @@ -1911,4 +1912,10 @@ def test_add_validation(self):
{"spreadsheetId": self.spreadsheet.id, "replies": [{}]},
)

self.assertRaises(APIError, sheet.update, values="X", range_name="A1")
with self.assertRaises(APIError) as ex:
sheet.update(values="X", range_name="A1")

# Ensure that the exception is able to be pickled and unpickled
# Further ensure we are able to access the exception's properties after pickling
reloaded_exception = pickle.loads(pickle.dumps(ex.exception)) # nosec
self.assertEqual(reloaded_exception.args[0]["status"], "INVALID_ARGUMENT")
lavigne958 marked this conversation as resolved.
Show resolved Hide resolved