Skip to content

Commit 8c3230e

Browse files
authored
Merge pull request #47 from scrapinghub/kumo1568
Add type field to APIError for better matching errors
2 parents e9d8e1b + 8df7308 commit 8c3230e

File tree

2 files changed

+25
-4
lines changed

2 files changed

+25
-4
lines changed

scrapinghub/exceptions.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44
from requests import HTTPError
55

6+
from .legacy import APIError
67
from .hubstorage import ValueTooLarge as _ValueTooLarge
78

89

@@ -62,6 +63,15 @@ def wrapped(*args, **kwargs):
6263
elif 400 <= status_code < 500:
6364
raise ScrapinghubAPIError(http_error=exc)
6465
raise
66+
except APIError as exc:
67+
msg = exc.args[0]
68+
if exc._type == APIError.ERR_NOT_FOUND:
69+
raise NotFound(msg)
70+
elif exc._type == APIError.ERR_VALUE_ERROR:
71+
raise ValueError(msg)
72+
elif exc._type == APIError.ERR_INVALID_USAGE:
73+
raise InvalidUsage(msg)
74+
raise ScrapinghubAPIError(msg)
6575
return wrapped
6676

6777

scrapinghub/legacy.py

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,8 @@ def _build_url(self, method, format):
9797
try:
9898
base_path = self.API_METHODS[method]
9999
except KeyError:
100-
raise APIError("Unknown method: {0}".format(method))
100+
raise APIError("Unknown method: {0}".format(method),
101+
_type=APIError.ERR_VALUE_ERROR)
101102
else:
102103
path = "{0}.{1}".format(base_path, format)
103104
return urljoin(self.url, path)
@@ -126,7 +127,8 @@ def _request(self, url, data, headers, format, raw, files=None):
126127
Raises APIError if json response have error status.
127128
"""
128129
if format not in ('json', 'jl') and not raw:
129-
raise APIError("format must be either json or jl")
130+
raise APIError("format must be either json or jl",
131+
_type=APIError.ERR_VALUE_ERROR)
130132

131133
if data is None and files is None:
132134
response = self._session.get(url, headers=headers)
@@ -145,7 +147,8 @@ def _decode_response(self, response, format, raw):
145147
if data['status'] == 'ok':
146148
return data
147149
elif data['status'] in ('error', 'badrequest'):
148-
raise APIError(data['message'])
150+
raise APIError(data['message'],
151+
_type=APIError.ERR_INVALID_USAGE)
149152
else:
150153
raise APIError("Unknown response status: {0[status]}".format(data))
151154
except KeyError:
@@ -394,4 +397,12 @@ def _add_params(self, params):
394397

395398

396399
class APIError(Exception):
397-
pass
400+
401+
ERR_DEFAULT = 0
402+
ERR_NOT_FOUND = 1
403+
ERR_VALUE_ERROR = 2
404+
ERR_INVALID_USAGE = 3
405+
406+
def __init__(self, message, _type=None):
407+
super(APIError, self).__init__(message)
408+
self._type = _type or self.ERR_DEFAULT

0 commit comments

Comments
 (0)