Skip to content
Draft
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
14 changes: 13 additions & 1 deletion src/linkup/_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -1370,7 +1370,19 @@ async def _async_handle_x402_payment(
return retry_response

def _raise_linkup_error(self, response: httpx.Response) -> None:
error_data = response.json()
try:
error_data = response.json()
except ValueError:
error_data = None

if not isinstance(error_data, dict):
error_data = {}
error_data = cast("dict[str, Any]", error_data)
if not isinstance(error_data.get("error"), dict):
raise LinkupUnknownError(
f"The Linkup API returned an unknown error ({response.status_code}).\n"
f"Original error message: ({response.text})."
)

if "error" in error_data:
error = error_data["error"]
Expand Down
52 changes: 52 additions & 0 deletions tests/unit/unexpected_error_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import httpx
import pytest
from pytest_mock import MockerFixture

import linkup


@pytest.mark.parametrize(
"body",
[
b"<html>Bad Gateway</html>",
b"",
b"Bad Gateway",
b"null",
b"[]",
b'{"message": "upstream unavailable"}',
b'{"error": "upstream unavailable"}',
b'{"error": null}',
b'{"error": {"message": "upstream unavailable"}}',
],
)
def test_unexpected_error_response(
body: bytes, mocker: MockerFixture, client: linkup.Client
) -> None:
mocker.patch("httpx.Client.request", return_value=httpx.Response(502, content=body))

with pytest.raises(linkup.UnknownError, match="502"):
client.search(query="test", depth="standard", output_type="searchResults")


@pytest.mark.asyncio
@pytest.mark.parametrize(
"body",
[
b"<html>Bad Gateway</html>",
b"",
b"Bad Gateway",
b"null",
b"[]",
b'{"message": "upstream unavailable"}',
b'{"error": "upstream unavailable"}',
b'{"error": null}',
b'{"error": {"message": "upstream unavailable"}}',
],
)
async def test_async_unexpected_error_response(
body: bytes, mocker: MockerFixture, client: linkup.Client
) -> None:
mocker.patch("httpx.AsyncClient.request", return_value=httpx.Response(502, content=body))

with pytest.raises(linkup.UnknownError, match="502"):
await client.async_search(query="test", depth="standard", output_type="searchResults")