Skip to content

Commit b08b135

Browse files
committed
Populate HTTPError with status code and error
1 parent aadba86 commit b08b135

File tree

3 files changed

+33
-2
lines changed

3 files changed

+33
-2
lines changed

serpapi/exceptions.py

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

25-
pass
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)
2629

2730

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

tests/test_exceptions.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
import pytest
2+
from unittest.mock import Mock, patch
3+
import requests
4+
import serpapi
5+
6+
7+
def test_http_error():
8+
"""Ensure that an HTTPError has the correct status code and error."""
9+
mock_response = Mock()
10+
mock_response.status_code = 401
11+
mock_response.json.return_value = { "error": "Invalid API key" }
12+
13+
requests_error = requests.exceptions.HTTPError(response=mock_response, request=Mock())
14+
http_error = serpapi.HTTPError(requests_error)
15+
16+
assert http_error.status_code == 401
17+
assert http_error.error == "Invalid API key"
18+
assert http_error.response == mock_response

tests/test_integration.py

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,8 +26,10 @@ def test_account_without_credentials():
2626

2727
def test_account_with_bad_credentials(invalid_key_client):
2828
"""Ensure that an HTTPError is raised when account is accessed with invalid API Credentials."""
29-
with pytest.raises(serpapi.HTTPError):
29+
with pytest.raises(serpapi.HTTPError) as exc_info:
3030
invalid_key_client.account()
31+
32+
assert exc_info.value.response.status_code == 401
3133

3234

3335
def test_account_with_credentials(client):
@@ -38,6 +40,14 @@ def test_account_with_credentials(client):
3840
assert isinstance(account, dict)
3941

4042

43+
def test_search_with_missing_params(client):
44+
with pytest.raises(serpapi.HTTPError) as exc_info:
45+
client.search({ "q": "" })
46+
47+
assert exc_info.value.status_code == 400
48+
assert "Missing query `q` parameter" in exc_info.value.error
49+
50+
4151
def test_coffee_search(coffee_search):
4252
assert isinstance(coffee_search, serpapi.SerpResults)
4353
assert hasattr(coffee_search, "__getitem__")

0 commit comments

Comments
 (0)