Skip to content

Commit cbd9411

Browse files
committed
Handle edge cases in HTTPError
1 parent f6a719b commit cbd9411

File tree

2 files changed

+17
-7
lines changed

2 files changed

+17
-7
lines changed

serpapi/exceptions.py

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -22,10 +22,21 @@ class SearchIDNotProvided(ValueError, SerpApiError):
2222
class HTTPError(requests.exceptions.HTTPError, SerpApiError):
2323
"""HTTP Error."""
2424

25-
def __init__(self, http_error_exception: requests.exceptions.HTTPError):
26-
self.status_code = http_error_exception.response.status_code
27-
self.error = http_error_exception.response.json().get("error", None)
28-
super().__init__(*http_error_exception.args, response=http_error_exception.response, request=http_error_exception.request)
25+
def __init__(self, original_exception):
26+
if (isinstance(original_exception, requests.exceptions.HTTPError)):
27+
http_error_exception: requests.exceptions.HTTPError = original_exception
28+
29+
self.status_code = http_error_exception.response.status_code
30+
try:
31+
self.error = http_error_exception.response.json().get("error", None)
32+
except requests.exceptions.JSONDecodeError:
33+
self.error = None
34+
else:
35+
self.status_code = -1
36+
self.error = None
37+
38+
super().__init__(*original_exception.args, response=getattr(original_exception, 'response', None), request=getattr(original_exception, 'request', None))
39+
2940

3041

3142
class HTTPConnectionError(HTTPError, requests.exceptions.ConnectionError, SerpApiError):

tests/test_exceptions.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
1-
import pytest
2-
from unittest.mock import Mock, patch
1+
from unittest.mock import Mock
32
import requests
43
import serpapi
54

@@ -15,4 +14,4 @@ def test_http_error():
1514

1615
assert http_error.status_code == 401
1716
assert http_error.error == "Invalid API key"
18-
assert http_error.response == mock_response
17+
assert http_error.response == mock_response

0 commit comments

Comments
 (0)