diff --git a/MIGRATION.md b/MIGRATION.md index 8825e9ba2..4c0348061 100644 --- a/MIGRATION.md +++ b/MIGRATION.md @@ -160,3 +160,30 @@ The client constructors of `supabase_auth`, `postgrest`, `storage3` and `supabas `request_timeout` is in seconds and limits how long a request may go without progress. Set it with the `request_timeout` argument of the client for every service, on `PostgrestClientOptions`, `AuthClientOptions`, `StorageClientOptions` or `FunctionsClientOptions` for one service, with `request_timeout()` on a database query, or with the `request_timeout` argument of `functions.invoke()`. None, the default, leaves the timeout to the HTTP client. A timed-out request raises `supabase.RequestTimeoutError`, a subclass of the built-in `TimeoutError`, instead of an httpx or aiohttp exception. This also applies to timeouts configured on the HTTP client. + +## One exception hierarchy + +Every exception the packages raise themselves inherits from `supabase_utils.errors.SupabaseError`, re-exported as `supabase.SupabaseError`, so `except SupabaseError` catches any failure the SDK reports. The hierarchy is described in the [error handling](src/supabase/README.md#error-handling) section of the README. The realtime connection is the exception: a lost websocket still surfaces as the `websockets.ConnectionClosed` or built-in `TimeoutError` that failed it, as before. + +Errors a service answered with inherit from `SupabaseAPIError` and expose the HTTP status as `status_code`, with the `response` next to it. The `status` attributes are renamed and the constructors take the status as a keyword argument. + +| Package | Before | After | +| -------------------- | ----------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | +| `supabase_auth` | `AuthApiError.status` | `AuthApiError.status_code` | +| `supabase_auth` | `AuthUnknownError.status`, `AuthUnknownError.data` | `AuthUnknownError.status_code`, `AuthUnknownError.response.content` | +| `supabase_auth` | `AuthRetryableError(message, status)` | `AuthRetryableError(message, status_code=...)`, a subclass of `AuthApiError` | +| `supabase_auth` | `AuthWeakPasswordError(message, status, reasons)` | `AuthWeakPasswordError(message, status_code=..., reasons=...)`, a subclass of `AuthApiError` | +| `supabase_auth` | `CustomAuthError`, `.status` on its subclasses | Removed. `AuthSessionMissingError` and the other errors the client raises on its own inherit `AuthError` directly and have no status | +| `postgrest` | `APIError(error)` | `APIError(error, status_code=..., response=...)`, with `status_code` and `response` attributes | +| `postgrest` | `str(error)` was the error dictionary | `str(error)` is the error message, `error.json()` is the dictionary | +| `storage3` | `StorageApiError(message=..., code=..., status=...)` | `StorageApiError(message, status_code=..., code=..., response=...)` | +| `storage3` | `StorageApiError.status` | `StorageApiError.status_code` | +| `supabase_functions` | `FunctionsError(message, name, status)`, `.name`, `.status` | `FunctionsError(message)`. Use `type(error).__name__` for the name; the status lives on the response errors | +| `supabase_functions` | `FunctionsHttpError(message, code)`, `.status` | `FunctionsHttpError(message, status_code=..., response=...)`, `.status_code` | +| `supabase_functions` | `FunctionsRelayError(message, code)`, `.status` | `FunctionsRelayError(message, status_code=..., response=...)`, `.status_code` | +| `realtime` | `realtime.client.MaxRetriesExceeded`, an `Exception` | `realtime.MaxRetriesExceeded`, a `RealtimeError` with a `retries` attribute | +| `realtime` | A failed `subscribe()` raised `Exception` | It raises `RealtimeError` | + +The auth errors are no longer dataclasses. `str(error)` returns the message for every error, as it does for the built-in exceptions, and `==` compares identity. + +A request that fails before a response can be read, because the connection failed, the request timed out or the HTTP client gave up on a redirect loop, raises `supabase.SupabaseTransportError` instead of an httpx or aiohttp exception, with that exception chained as `__cause__`. `RequestTimeoutError` is a subclass of it, and still a subclass of the built-in `TimeoutError`. Code that caught `httpx.ConnectError` or `aiohttp.ClientConnectorError` around a call of the SDK should catch `SupabaseTransportError` instead. The outcome of such a request is unknown, since it may have reached the service. diff --git a/sdk-compliance.yaml b/sdk-compliance.yaml index 89c79927a..905a4f567 100644 --- a/sdk-compliance.yaml +++ b/sdk-compliance.yaml @@ -1175,7 +1175,7 @@ features: storage.configuration.auto_retry: not_implemented storage.errors.error_codes: status: implemented - note: "The error code is exposed as the StorageApiError.code dataclass field, which is not registrable on its own since only properties are extracted as symbols." + note: "The error code is exposed as the StorageApiError.code attribute, which is not registrable on its own since only properties are extracted as symbols." symbols: - StorageApiError supporting_symbols: @@ -1415,7 +1415,6 @@ supporting_symbols: - AuthSessionMissingError - AuthUnknownError - AuthWeakPasswordError - - CustomAuthError - UserDoesNotExistError - WeakPasswordReasons - RawApiError @@ -1441,6 +1440,12 @@ supporting_symbols: - FunctionsRelayError - AuthorizationError - NotConnectedError + - MaxRetriesExceeded + - RealtimeError + - SupabaseError + - SupabaseAPIError + - SupabaseTransportError + - RequestTimeoutError - ChannelEvents - ChannelStates - RealtimeSubscribeStates diff --git a/src/auth/src/supabase_auth/__init__.py b/src/auth/src/supabase_auth/__init__.py index d101b7692..591b76f59 100644 --- a/src/auth/src/supabase_auth/__init__.py +++ b/src/auth/src/supabase_auth/__init__.py @@ -12,7 +12,6 @@ AuthSessionMissingError, AuthUnknownError, AuthWeakPasswordError, - CustomAuthError, ErrorCode, UserDoesNotExistError, ) @@ -156,7 +155,6 @@ "CaptchaToken", "ClaimsResponse", "CreateOAuthClientParams", - "CustomAuthError", "EmailOtpType", "ErrorCode", "Factor", diff --git a/src/auth/src/supabase_auth/errors.py b/src/auth/src/supabase_auth/errors.py index c1f81c3f2..2594ed149 100644 --- a/src/auth/src/supabase_auth/errors.py +++ b/src/auth/src/supabase_auth/errors.py @@ -1,9 +1,13 @@ from __future__ import annotations -from dataclasses import dataclass -from typing import Any, Literal +from typing import TYPE_CHECKING, Any, Literal from pydantic import BaseModel, TypeAdapter, ValidationError, field_validator +from supabase_utils.errors import SupabaseError +from supabase_utils.http.errors import SupabaseAPIError + +if TYPE_CHECKING: + from supabase_utils.http.request import Response ErrorCode = Literal[ "unexpected_failure", @@ -124,94 +128,107 @@ def get_error_message(self) -> str: ) -@dataclass -class AuthError(Exception): - message: str - code: ErrorCode | None +class AuthError(SupabaseError): + """Raised when an auth operation fails. + A plain `AuthError` is a failure the client raised on its own, such as a + missing session. A failure the auth service reported is an `AuthApiError`. + `code` is one of `ErrorCode` when the service named the failure, see + https://supabase.com/docs/guides/auth/debugging/error-codes. + """ -@dataclass -class AuthApiError(AuthError): - status: int +class AuthApiError(AuthError, SupabaseAPIError): + """Raised when the auth service answered a request with an error.""" -@dataclass -class AuthUnknownError(AuthError): - data: bytes - status: int + def __init__( + self, + message: str, + *, + status_code: int, + code: ErrorCode | None = None, + response: Response | None = None, + ) -> None: + super().__init__(message, status_code=status_code, code=code, response=response) -@dataclass -class CustomAuthError(AuthError): - status: int +class AuthUnknownError(AuthError, SupabaseAPIError): + """Raised when the auth service answered with an error that could not be + parsed. The body is `response.content`.""" + + def __init__( + self, + message: str, + *, + status_code: int, + code: ErrorCode | None = None, + response: Response | None = None, + ) -> None: + super().__init__(message, status_code=status_code, code=code, response=response) -class UserDoesNotExistError(CustomAuthError): +class UserDoesNotExistError(AuthError): def __init__(self) -> None: super().__init__( - message="User does not exist for the provided access token", - status=404, + "User does not exist for the provided access token", code="user_not_found", ) -class AuthSessionMissingError(CustomAuthError): +class AuthSessionMissingError(AuthError): def __init__(self) -> None: - super().__init__( - message="Auth session missing!", - status=400, - code=None, - ) + super().__init__("Auth session missing!") -class AuthInvalidCredentialsError(CustomAuthError): +class AuthInvalidCredentialsError(AuthError): def __init__(self, message: str) -> None: - super().__init__( - message=message, - status=400, - code=None, - ) + super().__init__(message) -class AuthImplicitGrantRedirectError(CustomAuthError): +class AuthImplicitGrantRedirectError(AuthError): def __init__( self, message: str, error: str | None = None, code: str | None = None, ) -> None: - super().__init__( - message=message, - status=500, - code=None, - ) + super().__init__(message) self.detail_error = error self.detail_code = code -class AuthRetryableError(CustomAuthError): - def __init__(self, message: str, status: int) -> None: - super().__init__( - message, - status=status, - code=None, - ) +class AuthRetryableError(AuthApiError): + """Raised when the auth service answered with a status that is worth + retrying, such as a gateway error.""" + + def __init__( + self, + message: str, + *, + status_code: int, + response: Response | None = None, + ) -> None: + super().__init__(message, status_code=status_code, response=response) -class AuthWeakPasswordError(CustomAuthError): - def __init__(self, message: str, status: int, reasons: list[str]) -> None: +class AuthWeakPasswordError(AuthApiError): + """Raised when the auth service rejected a password. `reasons` lists what + it lacked.""" + + def __init__( + self, + message: str, + *, + status_code: int, + reasons: list[str], + response: Response | None = None, + ) -> None: super().__init__( - message=message, - status=status, - code="weak_password", + message, status_code=status_code, code="weak_password", response=response ) self.reasons = reasons -class AuthInvalidJwtError(CustomAuthError): +class AuthInvalidJwtError(AuthError): def __init__(self, message: str) -> None: - super().__init__( - message=message, - status=400, - code="invalid_jwt", - ) + super().__init__(message, code="invalid_jwt") diff --git a/src/auth/src/supabase_auth/helpers.py b/src/auth/src/supabase_auth/helpers.py index b05f074d3..12d7ede19 100644 --- a/src/auth/src/supabase_auth/helpers.py +++ b/src/auth/src/supabase_auth/helpers.py @@ -115,15 +115,27 @@ def _handle_error_response(response: Response) -> AuthError: raw_error = RawApiError.model_validate_json(response.content) except ValidationError: return AuthUnknownError( - message="Unexpected error: Unable to parse API error", + "Unexpected error: Unable to parse API error", + status_code=response.status, code="unexpected_failure", - status=response.status, - data=response.content, + response=response, + ) + if not response.is_error or response.status in { + 502, + 503, + 504, + 520, + 521, + 522, + 523, + 524, + 530, + }: + return AuthRetryableError( + raw_error.get_error_message(), + status_code=response.status, + response=response, ) - if not response.is_error: - return AuthRetryableError(raw_error.get_error_message(), response.status) - if response.status in {502, 503, 504, 520, 521, 522, 523, 524, 530}: - return AuthRetryableError(raw_error.get_error_message(), response.status) error_code = None response_api_version = parse_response_api_version(response) @@ -142,21 +154,24 @@ def _handle_error_response(response: Response) -> AuthError: and raw_error.weak_password.reasons ): return AuthWeakPasswordError( - message=raw_error.get_error_message(), - status=response.status, + raw_error.get_error_message(), + status_code=response.status, reasons=raw_error.weak_password.reasons, + response=response, ) if error_code == "weak_password": return AuthWeakPasswordError( raw_error.get_error_message(), - status=response.status, + status_code=response.status, reasons=raw_error.weak_password.reasons if raw_error.weak_password else [], + response=response, ) return AuthApiError( raw_error.get_error_message(), - status=response.status or 500, + status_code=response.status or 500, code=error_code, + response=response, ) diff --git a/src/auth/tests/test_errors.py b/src/auth/tests/test_errors.py index ee57e8c6b..54616478c 100644 --- a/src/auth/tests/test_errors.py +++ b/src/auth/tests/test_errors.py @@ -1,10 +1,112 @@ -from supabase_auth.errors import AuthError, UserDoesNotExistError +import pickle + +from supabase_utils.errors import SupabaseError +from supabase_utils.http.errors import SupabaseAPIError +from supabase_utils.http.headers import Headers +from supabase_utils.http.request import Request, Response +from yarl import URL + +from supabase_auth.errors import ( + AuthApiError, + AuthError, + AuthImplicitGrantRedirectError, + AuthInvalidCredentialsError, + AuthInvalidJwtError, + AuthRetryableError, + AuthSessionMissingError, + AuthUnknownError, + AuthWeakPasswordError, + UserDoesNotExistError, +) + + +def make_response(status: int, content: bytes = b"{}") -> Response: + return Response( + headers=Headers.empty(), + content=content, + status=status, + request=Request( + url=URL("https://example.com/auth/v1/token"), + method="POST", + headers=Headers.empty(), + content=None, + delay=None, + ), + ) def test_user_does_not_exist_error_never_carries_the_token() -> None: error = UserDoesNotExistError() assert isinstance(error, AuthError) assert error.message == "User does not exist for the provided access token" + assert str(error) == error.message assert error.code == "user_not_found" - assert error.status == 404 assert not hasattr(error, "access_token") + + +def test_auth_error_is_a_supabase_error() -> None: + assert issubclass(AuthError, SupabaseError) + assert not issubclass(AuthError, SupabaseAPIError) + + +def test_client_side_errors_are_not_api_errors() -> None: + for error in ( + AuthSessionMissingError(), + AuthInvalidCredentialsError("bad"), + AuthImplicitGrantRedirectError("bad url", error="e", code="c"), + AuthInvalidJwtError("bad jwt"), + UserDoesNotExistError(), + ): + assert isinstance(error, AuthError) + assert not isinstance(error, SupabaseAPIError) + assert str(error) == error.message + + +def test_api_error_carries_the_response() -> None: + response = make_response(400, b'{"msg": "Invalid login"}') + error = AuthApiError( + "Invalid login", + status_code=400, + code="invalid_credentials", + response=response, + ) + assert isinstance(error, SupabaseAPIError) + assert str(error) == "Invalid login" + assert error.status_code == 400 + assert error.code == "invalid_credentials" + assert error.response is response + + +def test_retryable_and_weak_password_errors_are_api_errors() -> None: + retryable = AuthRetryableError("down", status_code=503) + weak = AuthWeakPasswordError("weak", status_code=422, reasons=["length"]) + assert isinstance(retryable, AuthApiError) + assert retryable.code is None + assert isinstance(weak, AuthApiError) + assert weak.code == "weak_password" + assert weak.reasons == ["length"] + + +def test_unknown_error_keeps_the_body_on_the_response() -> None: + response = make_response(500, b"") + error = AuthUnknownError( + "Unexpected error", + status_code=500, + code="unexpected_failure", + response=response, + ) + assert isinstance(error, SupabaseAPIError) + assert error.response is not None + assert error.response.content == b"" + + +def test_errors_can_be_pickled() -> None: + weak = AuthWeakPasswordError("weak", status_code=422, reasons=["length"]) + copy = pickle.loads(pickle.dumps(weak)) + assert isinstance(copy, AuthWeakPasswordError) + assert str(copy) == "weak" + assert copy.status_code == 422 + assert copy.reasons == ["length"] + assert isinstance( + pickle.loads(pickle.dumps(AuthSessionMissingError())), AuthSessionMissingError + ) diff --git a/src/auth/tests/test_helpers.py b/src/auth/tests/test_helpers.py index e62fddc37..d567bd161 100644 --- a/src/auth/tests/test_helpers.py +++ b/src/auth/tests/test_helpers.py @@ -165,7 +165,7 @@ def test_handle_error_response_legacy_weak_password_without_error_code() -> None assert isinstance(result, AuthWeakPasswordError) assert result.message == "Password too weak" - assert result.status == 422 + assert result.status_code == 422 assert result.reasons == ["length", "characters"] @@ -192,7 +192,7 @@ def test_handle_error_response_legacy_weak_password_ignores_malformed_reasons( assert isinstance(result, AuthApiError) assert not isinstance(result, AuthWeakPasswordError) assert result.message == "Password too weak" - assert result.status == 422 + assert result.status_code == 422 def test_handle_error_response_weak_password_with_error_code() -> None: diff --git a/src/functions/src/supabase_functions/errors.py b/src/functions/src/supabase_functions/errors.py index 066199125..d9f9993a4 100644 --- a/src/functions/src/supabase_functions/errors.py +++ b/src/functions/src/supabase_functions/errors.py @@ -3,27 +3,25 @@ from typing import TYPE_CHECKING from pydantic import ValidationError +from supabase_utils.errors import SupabaseError +from supabase_utils.http.errors import SupabaseAPIError from supabase_utils.types import JSONParser if TYPE_CHECKING: from supabase_utils.http.request import Response -class FunctionsError(Exception): - def __init__(self, message: str, name: str, status: int) -> None: - super().__init__(message) - self.message = message - self.name = name - self.status = status +class FunctionsError(SupabaseError): + """Raised when invoking an edge function fails.""" -class FunctionsHttpError(FunctionsError): - def __init__(self, message: str, code: int | None = None) -> None: - super().__init__( - message, - "FunctionsHttpError", - 400 if code is None else code, - ) +class FunctionsHttpError(FunctionsError, SupabaseAPIError): + """Raised when the edge function answered with an error status.""" + + +class FunctionsRelayError(FunctionsError, SupabaseAPIError): + """Raised when the relay in front of the edge function answered with an + error, marked by the `x-relay-error` header.""" def _is_relay_error(response: Response) -> bool: @@ -47,22 +45,14 @@ def _error_message_from(response: Response) -> str | None: def _on_error_response(response: Response) -> FunctionsHttpError | FunctionsRelayError: if _is_relay_error(response): return FunctionsRelayError( - response.content.decode("utf-8", errors="replace"), code=response.status + response.content.decode("utf-8", errors="replace"), + status_code=response.status, + response=response, ) return FunctionsHttpError( _error_message_from(response) or "An error occurred while requesting your edge function at " f"{str(response.request.url)!r}.", - response.status, + status_code=response.status, + response=response, ) - - -class FunctionsRelayError(FunctionsError): - """Base exception for relay errors.""" - - def __init__(self, message: str, code: int | None = None) -> None: - super().__init__( - message, - "FunctionsRelayError", - 400 if code is None else code, - ) diff --git a/src/functions/tests/_async/test_function_client.py b/src/functions/tests/_async/test_function_client.py index d1904725b..138c0f411 100644 --- a/src/functions/tests/_async/test_function_client.py +++ b/src/functions/tests/_async/test_function_client.py @@ -115,7 +115,7 @@ async def test_invoke_with_http_error() -> None: client = client_returning(content=b'{"error": "Custom error message"}', status=400) with pytest.raises(FunctionsHttpError, match="Custom error message") as exc_info: await client.invoke("test-function") - assert exc_info.value.status == 400 + assert exc_info.value.status_code == 400 async def test_invoke_http_error_with_non_json_body() -> None: @@ -130,7 +130,7 @@ async def test_invoke_http_error_with_empty_body() -> None: FunctionsHttpError, match="An error occurred while requesting" ) as exc_info: await client.invoke("test-function") - assert exc_info.value.status == 500 + assert exc_info.value.status_code == 500 async def test_invoke_with_relay_error() -> None: @@ -152,7 +152,7 @@ async def test_invoke_relay_error_on_non_2xx_status() -> None: with pytest.raises(FunctionsRelayError, match="relay exploded") as exc_info: await client.invoke("test-function") assert not isinstance(exc_info.value, FunctionsHttpError) - assert exc_info.value.status == 546 + assert exc_info.value.status_code == 546 async def test_invoke_invalid_function_name() -> None: diff --git a/src/functions/tests/_sync/test_function_client.py b/src/functions/tests/_sync/test_function_client.py index ab79a289e..379a24773 100644 --- a/src/functions/tests/_sync/test_function_client.py +++ b/src/functions/tests/_sync/test_function_client.py @@ -115,7 +115,7 @@ def test_invoke_with_http_error() -> None: client = client_returning(content=b'{"error": "Custom error message"}', status=400) with pytest.raises(FunctionsHttpError, match="Custom error message") as exc_info: client.invoke("test-function") - assert exc_info.value.status == 400 + assert exc_info.value.status_code == 400 def test_invoke_http_error_with_non_json_body() -> None: @@ -130,7 +130,7 @@ def test_invoke_http_error_with_empty_body() -> None: FunctionsHttpError, match="An error occurred while requesting" ) as exc_info: client.invoke("test-function") - assert exc_info.value.status == 500 + assert exc_info.value.status_code == 500 def test_invoke_with_relay_error() -> None: @@ -152,7 +152,7 @@ def test_invoke_relay_error_on_non_2xx_status() -> None: with pytest.raises(FunctionsRelayError, match="relay exploded") as exc_info: client.invoke("test-function") assert not isinstance(exc_info.value, FunctionsHttpError) - assert exc_info.value.status == 546 + assert exc_info.value.status_code == 546 def test_invoke_invalid_function_name() -> None: diff --git a/src/functions/tests/test_errors.py b/src/functions/tests/test_errors.py index b66e6dc0a..553f92897 100644 --- a/src/functions/tests/test_errors.py +++ b/src/functions/tests/test_errors.py @@ -1,4 +1,8 @@ +import pickle + import pytest +from supabase_utils.errors import SupabaseError +from supabase_utils.http.errors import SupabaseAPIError from supabase_utils.http.headers import Headers from supabase_utils.http.request import Request, Response from yarl import URL @@ -29,54 +33,43 @@ def make_response( ) -@pytest.mark.parametrize( - ("error_class", "expected_name", "expected_status"), - [ - (FunctionsError, "test_error", 500), - (FunctionsHttpError, "FunctionsHttpError", 400), - (FunctionsRelayError, "FunctionsRelayError", 400), - ], -) -def test_error_initialization( - error_class: type[FunctionsError], expected_name: str, expected_status: int -) -> None: - test_message = "Test error message" - if issubclass(error_class, (FunctionsHttpError, FunctionsRelayError)): - error: FunctionsError = error_class(test_message) - else: - error = error_class(test_message, expected_name, expected_status) - - assert str(error) == test_message - assert error.message == test_message - assert error.name == expected_name - assert error.status == expected_status - assert isinstance(error, Exception) - +def test_functions_error_is_a_supabase_error() -> None: + error = FunctionsError("boom", code="x") + assert isinstance(error, SupabaseError) + assert not isinstance(error, SupabaseAPIError) + assert str(error) == "boom" + assert error.message == "boom" + assert error.code == "x" -def test_functions_error_inheritance() -> None: - # Test that all error classes inherit from FunctionsError - assert issubclass(FunctionsHttpError, FunctionsError) - assert issubclass(FunctionsRelayError, FunctionsError) +@pytest.mark.parametrize("error_class", [FunctionsHttpError, FunctionsRelayError]) +def test_response_errors_are_api_errors( + error_class: type[FunctionsHttpError | FunctionsRelayError], +) -> None: + response = make_response(b"nope", status=502) + error = error_class("Test error message", status_code=502, response=response) + assert isinstance(error, FunctionsError) + assert isinstance(error, SupabaseAPIError) + assert str(error) == "Test error message" + assert error.message == "Test error message" + assert error.status_code == 502 + assert error.code is None + assert error.response is response -def test_error_as_exception() -> None: - # Test that errors can be raised and caught - test_message = "Test exception" - # Test base error - with pytest.raises(FunctionsError) as exc_info: - raise FunctionsError(test_message, "test_error", 500) - assert str(exc_info.value) == test_message +def test_relay_error_is_not_an_http_error() -> None: + assert not issubclass(FunctionsRelayError, FunctionsHttpError) + assert not issubclass(FunctionsHttpError, FunctionsRelayError) - # Test HTTP error - with pytest.raises(FunctionsHttpError) as exc_info: - raise FunctionsHttpError(test_message) - assert str(exc_info.value) == test_message - # Test Relay error - with pytest.raises(FunctionsRelayError) as exc_info: - raise FunctionsRelayError(test_message) - assert str(exc_info.value) == test_message +def test_errors_can_be_pickled() -> None: + error = FunctionsHttpError("boom", status_code=404, response=make_response(b"")) + copy = pickle.loads(pickle.dumps(error)) + assert isinstance(copy, FunctionsHttpError) + assert str(copy) == "boom" + assert copy.status_code == 404 + assert copy.response is not None + assert copy.response.status == 500 def test_error_message_types() -> None: @@ -90,7 +83,7 @@ def test_error_message_types() -> None: ] for message in test_cases: - error = FunctionsError(message, "test", 500) + error = FunctionsError(message) assert error.message == message @@ -117,7 +110,9 @@ def test_on_error_response_http_error() -> None: error = _on_error_response(make_response(b'{"error": "boom"}', status=404)) assert isinstance(error, FunctionsHttpError) assert error.message == "boom" - assert error.status == 404 + assert error.status_code == 404 + assert error.response is not None + assert error.response.status == 404 def test_on_error_response_http_error_fallback_message() -> None: @@ -136,4 +131,4 @@ def test_on_error_response_relay_error_keeps_raw_text() -> None: ) assert isinstance(error, FunctionsRelayError) assert error.message == '{"error": "relay"}' - assert error.status == 546 + assert error.status_code == 546 diff --git a/src/postgrest/src/postgrest/exceptions.py b/src/postgrest/src/postgrest/exceptions.py index cfe4b1c64..5b99beebd 100644 --- a/src/postgrest/src/postgrest/exceptions.py +++ b/src/postgrest/src/postgrest/exceptions.py @@ -1,7 +1,12 @@ -from typing import Any, override +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, override from pydantic import BaseModel -from supabase_utils.http.request import Response +from supabase_utils.http.errors import SupabaseAPIError + +if TYPE_CHECKING: + from supabase_utils.http.request import Response class APIErrorFromJSON(BaseModel): @@ -20,28 +25,35 @@ class APIErrorFromJSON(BaseModel): """The error details.""" -class APIError(Exception): - """ - Base exception for all API errors. +class APIError(SupabaseAPIError): + """Raised when PostgREST answered a request with an error. + + `message`, `code`, `hint` and `details` are the fields of the error body, + see https://postgrest.org/en/stable/references/errors.html. """ _raw_error: dict[str, Any] - message: str | None - """The error message.""" - code: str | None - """The error code.""" hint: str | None """The error hint.""" details: Any """The error details.""" - def __init__(self, error: dict[str, Any]) -> None: + def __init__( + self, + error: dict[str, Any], + *, + status_code: int, + response: Response | None = None, + ) -> None: self._raw_error = error - self.message = error.get("message") - self.code = error.get("code") self.hint = error.get("hint") self.details = error.get("details") - super().__init__(str(self)) + super().__init__( + error.get("message") or "Unknown error", + status_code=status_code, + code=error.get("code"), + response=response, + ) @override def __repr__(self) -> str: diff --git a/src/postgrest/src/postgrest/request_builder.py b/src/postgrest/src/postgrest/request_builder.py index a74c677de..77ad1c67d 100644 --- a/src/postgrest/src/postgrest/request_builder.py +++ b/src/postgrest/src/postgrest/request_builder.py @@ -666,8 +666,18 @@ def _api_error(response: Response) -> APIError: try: json_obj = APIErrorFromJSON.model_validate_json(response.content) except ValidationError: - return APIError(generate_default_error_message(response)) - return APIError(dict(json_obj)) + error = generate_default_error_message(response) + else: + error = dict(json_obj) + return APIError(error, status_code=response.status, response=response) + + +def _invalid_response_error(response: Response) -> APIError: + return APIError( + generate_default_error_message(response), + status_code=response.status, + response=response, + ) def _can_retry(resp: Response, retry_enabled: bool, attempt_count: int) -> bool: @@ -727,7 +737,7 @@ def execute(self) -> HttpMethod[APIResponse]: try: return APIResponse.from_http_request_response(r) except ValidationError as e: - raise APIError(generate_default_error_message(r)) from e + raise _invalid_response_error(r) from e class SingleRequestBuilder[HttpIO: (SyncHttpIO, AsyncHttpIO)]( @@ -747,10 +757,12 @@ def execute(self) -> HttpMethod[SingleAPIResponse]: :class:`APIError` If the API raised an error. """ response = yield from send_with_retry(self.request) - if response.is_success: - return SingleAPIResponse.from_http_request_response(response) - else: + if not response.is_success: raise _api_error(response) + try: + return SingleAPIResponse.from_http_request_response(response) + except ValidationError as e: + raise _invalid_response_error(response) from e class TextRequestBuilder[HttpIO: (SyncHttpIO, AsyncHttpIO)](BaseRequestClient[HttpIO]): @@ -795,7 +807,7 @@ def execute(self) -> HttpMethod[SingleAPIResponse | None]: try: parsed = APIResponse.from_http_request_response(response) except ValidationError as e: - raise APIError(generate_default_error_message(response)) from e + raise _invalid_response_error(response) from e if len(parsed.data) == 0: return None if len(parsed.data) == 1: @@ -807,7 +819,8 @@ def execute(self) -> HttpMethod[SingleAPIResponse | None]: "code": "406", "hint": "Please check traceback of the code", "details": "The result contains more than one row.", - } + }, + status_code=406, ) else: raise _api_error(response) @@ -866,7 +879,7 @@ def execute(self) -> HttpMethod[APIResponse]: try: return APIResponse.from_http_request_response(r) except ValidationError as e: - raise APIError(generate_default_error_message(r)) from e + raise _invalid_response_error(r) from e class RPCCountRequestBuilder[HttpIO: (SyncHttpIO, AsyncHttpIO)]( diff --git a/src/postgrest/tests/test_api_error.py b/src/postgrest/tests/test_api_error.py index 8065b1c01..322ec7046 100644 --- a/src/postgrest/tests/test_api_error.py +++ b/src/postgrest/tests/test_api_error.py @@ -1,8 +1,11 @@ +import pickle from typing import Any import pytest from httpx import Client, MockTransport, Request, Response +from supabase_utils.errors import SupabaseError from supabase_utils.http.adapters.httpx import HttpxSession +from supabase_utils.http.errors import SupabaseAPIError from postgrest import APIError, SyncPostgrestClient @@ -33,3 +36,85 @@ def handler(request: Request) -> Response: assert exc_info.value.message == message assert exc_info.value.details == details + + +def test_api_error_is_a_supabase_api_error() -> None: + assert issubclass(APIError, SupabaseAPIError) + assert issubclass(APIError, SupabaseError) + + +def test_api_error_carries_status_code_and_response() -> None: + body = b'{"code": "PGRST116", "details": "0 rows", "hint": null, "message": "one row expected"}' + + def handler(request: Request) -> Response: + return Response(406, content=body) + + with Client(transport=MockTransport(handler)) as http: + client = SyncPostgrestClient( + "https://example.com", http_session=HttpxSession(client=http) + ) + with pytest.raises(APIError) as exc_info: + client.from_("test").select("a").execute() + + error = exc_info.value + assert str(error) == "one row expected" + assert error.message == "one row expected" + assert error.code == "PGRST116" + assert error.hint is None + assert error.details == "0 rows" + assert error.status_code == 406 + assert error.response is not None + assert error.response.content == body + assert error.json() == { + "code": "PGRST116", + "details": "0 rows", + "hint": None, + "message": "one row expected", + } + + +def test_api_error_without_json_body_keeps_the_status() -> None: + def handler(request: Request) -> Response: + return Response(502, content=b"bad gateway") + + with Client(transport=MockTransport(handler)) as http: + client = SyncPostgrestClient( + "https://example.com", http_session=HttpxSession(client=http) + ) + with pytest.raises(APIError) as exc_info: + client.from_("test").select("a").execute() + + error = exc_info.value + assert error.status_code == 502 + assert error.code == "502" + assert error.message == "JSON could not be generated" + assert "bad gateway" in str(error.details) + + +def test_api_error_can_be_pickled() -> None: + error = APIError({"message": "m", "code": "c", "hint": "h"}, status_code=400) + clone = pickle.loads(pickle.dumps(error)) + assert isinstance(clone, APIError) + assert str(clone) == "m" + assert clone.code == "c" + assert clone.hint == "h" + assert clone.status_code == 400 + assert clone.json() == error.json() + + +def test_single_with_invalid_body_raises_api_error() -> None: + def handler(request: Request) -> Response: + return Response(200, content=b"not json") + + with Client(transport=MockTransport(handler)) as http: + client = SyncPostgrestClient( + "https://example.com", http_session=HttpxSession(client=http) + ) + with pytest.raises(APIError) as exc_info: + client.from_("test").select("a").single().execute() + + error = exc_info.value + assert error.status_code == 200 + assert error.message == "JSON could not be generated" + assert error.response is not None + assert error.response.content == b"not json" diff --git a/src/realtime/src/realtime/__init__.py b/src/realtime/src/realtime/__init__.py index eecffc71b..5b1f57cb9 100644 --- a/src/realtime/src/realtime/__init__.py +++ b/src/realtime/src/realtime/__init__.py @@ -7,7 +7,12 @@ from .channel import RealtimeChannel, RealtimeChannelOptions from .client import RealtimeClient, connect_once -from .exceptions import AuthorizationError, NotConnectedError +from .exceptions import ( + AuthorizationError, + MaxRetriesExceeded, + NotConnectedError, + RealtimeError, +) from .message import ( AccessTokenMessage, AccessTokenPayload, @@ -96,6 +101,7 @@ "HeartbeatMessage", "HeartbeatPayload", "JoinMessage", + "MaxRetriesExceeded", "Message", "NotConnectedError", "Payload", @@ -124,6 +130,7 @@ "RealtimeChannelOptionsPayload", "RealtimeChannelPresenceConfig", "RealtimeClient", + "RealtimeError", "RealtimePostgresChangesListenEvent", "RealtimePresence", "RealtimePresenceJoinPayload", diff --git a/src/realtime/src/realtime/channel.py b/src/realtime/src/realtime/channel.py index 348fa7073..d81c2cfd9 100644 --- a/src/realtime/src/realtime/channel.py +++ b/src/realtime/src/realtime/channel.py @@ -9,6 +9,7 @@ import websockets +from .exceptions import RealtimeError from .message import ( BroadcastMessage, ChannelCloseMessage, @@ -237,7 +238,7 @@ async def subscribe(self) -> ReplyMessage: msg = await self.socket._send(message) logger.info("Subscribe reply: %r", msg) if msg.payload.status != "ok": - raise Exception( + raise RealtimeError( f"error while subscribing to channel: {msg.payload.response!r}" ) self.join_ref = join_ref diff --git a/src/realtime/src/realtime/client.py b/src/realtime/src/realtime/client.py index c276def6e..b4ffc9d87 100644 --- a/src/realtime/src/realtime/client.py +++ b/src/realtime/src/realtime/client.py @@ -6,11 +6,13 @@ import websockets from pydantic import ValidationError +from supabase_utils.http.errors import SupabaseTransportError from websockets.asyncio.client import ClientConnection from yarl import URL from ._redact import RedactingLoggerAdapter from .channel import RealtimeChannel, RealtimeChannelOptions +from .exceptions import MaxRetriesExceeded from .message import Message, ReplyMessage from .types import ( DEFAULT_HEARTBEAT_INTERVAL, @@ -112,10 +114,6 @@ async def __aexit__( MAX_RECONNECT_DELAY = 60 -class MaxRetriesExceeded(Exception): - pass - - def exponential_delay(max_retries: int, retry_count: int) -> float | None: if retry_count >= max_retries: return None @@ -137,7 +135,12 @@ async def automatically_reconnect( connected_at = loop.time() await client_handler(client) break - except (websockets.ConnectionClosed, TimeoutError, OSError) as e: + except ( + websockets.ConnectionClosed, + TimeoutError, + OSError, + SupabaseTransportError, + ) as e: if ( connected_at is not None and loop.time() - connected_at >= MAX_RECONNECT_DELAY diff --git a/src/realtime/src/realtime/exceptions.py b/src/realtime/src/realtime/exceptions.py index b3f8ad73e..c00fce732 100644 --- a/src/realtime/src/realtime/exceptions.py +++ b/src/realtime/src/realtime/exceptions.py @@ -1,29 +1,36 @@ -from typing import override +from supabase_utils.errors import SupabaseError -class NotConnectedError(Exception): +class RealtimeError(SupabaseError): + """Raised when a realtime operation fails.""" + + +class NotConnectedError(RealtimeError): """ Raised when operations requiring a connection are executed when socket is not connected """ def __init__(self, func_name: str) -> None: - super().__init__(func_name) + super().__init__( + "A WS connection has not been established. Ensure you call " + "AsyncRealtimeClient.connect() before calling " + f"AsyncRealtimeClient.{func_name}()" + ) self.offending_func_name: str = func_name - @override - def __str__(self) -> str: - return f"A WS connection has not been established. Ensure you call AsyncRealtimeClient.connect() before calling AsyncRealtimeClient.{self.offending_func_name}()" - -class AuthorizationError(Exception): +class AuthorizationError(RealtimeError): """ Raised when there is an authorization failure for private channels """ def __init__(self, message: str | None = None) -> None: - self.message: str = message or "Authorization failed for private channel" - super().__init__(self.message) + super().__init__(message or "Authorization failed for private channel") + + +class MaxRetriesExceeded(RealtimeError): + """Raised when reconnecting failed `retries` times in a row.""" - @override - def __str__(self) -> str: - return self.message + def __init__(self, retries: int) -> None: + super().__init__(f"Reconnecting failed after {retries} attempts") + self.retries = retries diff --git a/src/realtime/tests/test_exceptions.py b/src/realtime/tests/test_exceptions.py new file mode 100644 index 000000000..399947ab3 --- /dev/null +++ b/src/realtime/tests/test_exceptions.py @@ -0,0 +1,44 @@ +import pickle + +import pytest +from supabase_utils.errors import SupabaseError + +from realtime import ( + AuthorizationError, + MaxRetriesExceeded, + NotConnectedError, + RealtimeError, +) + + +def test_realtime_errors_inherit_the_shared_root() -> None: + assert issubclass(RealtimeError, SupabaseError) + for error_class in (AuthorizationError, MaxRetriesExceeded, NotConnectedError): + assert issubclass(error_class, RealtimeError) + + +def test_not_connected_error_names_the_method() -> None: + error = NotConnectedError("send") + assert error.offending_func_name == "send" + assert "AsyncRealtimeClient.send()" in str(error) + assert str(error) == error.message + + +def test_authorization_error_has_a_default_message() -> None: + assert str(AuthorizationError()) == "Authorization failed for private channel" + assert str(AuthorizationError("nope")) == "nope" + + +def test_max_retries_exceeded_keeps_the_count() -> None: + error = MaxRetriesExceeded(3) + assert error.retries == 3 + assert str(error) == "Reconnecting failed after 3 attempts" + with pytest.raises(SupabaseError): + raise error + + +def test_errors_can_be_pickled() -> None: + clone = pickle.loads(pickle.dumps(NotConnectedError("send"))) + assert isinstance(clone, NotConnectedError) + assert clone.offending_func_name == "send" + assert str(clone) == str(NotConnectedError("send")) diff --git a/src/realtime/tests/test_reconnect_backoff_cap.py b/src/realtime/tests/test_reconnect_backoff_cap.py index d1c404226..269ceb093 100644 --- a/src/realtime/tests/test_reconnect_backoff_cap.py +++ b/src/realtime/tests/test_reconnect_backoff_cap.py @@ -1,12 +1,13 @@ from unittest.mock import AsyncMock, patch import pytest +from supabase_utils.http.errors import SupabaseTransportError +from supabase_utils.http.headers import Headers +from supabase_utils.http.request import Request +from yarl import URL -from realtime.client import ( - MaxRetriesExceeded, - automatically_reconnect, - exponential_delay, -) +from realtime import MaxRetriesExceeded +from realtime.client import automatically_reconnect, exponential_delay def test_exponential_delay_caps_each_retry_at_sixty_seconds() -> None: @@ -42,3 +43,34 @@ async def client_handler(client: object) -> None: 60, 60, ] + + +async def test_automatically_reconnect_retries_transport_errors_of_the_token_callback() -> ( + None +): + request = Request( + url=URL("https://example.com/auth/v1/token"), + method="POST", + headers=Headers.empty(), + content=None, + delay=None, + ) + + async def get_token() -> str: + raise SupabaseTransportError(request) + + async def client_handler(client: object) -> None: + return + + sleep = AsyncMock() + + with ( + patch("realtime.client.asyncio.sleep", sleep), + pytest.raises(MaxRetriesExceeded) as error, + ): + await automatically_reconnect( + "ws://localhost/realtime/v1", get_token, client_handler, max_retries=2 + ) + + assert isinstance(error.value.__cause__, SupabaseTransportError) + assert [call.args[0] for call in sleep.await_args_list] == [2] diff --git a/src/realtime/tests/test_reconnection.py b/src/realtime/tests/test_reconnection.py index b0b2613a3..ed1579ce3 100644 --- a/src/realtime/tests/test_reconnection.py +++ b/src/realtime/tests/test_reconnection.py @@ -9,9 +9,10 @@ from websockets.exceptions import ConnectionClosedOK from realtime import ( + MaxRetriesExceeded, RealtimeClient, ) -from realtime.client import MaxRetriesExceeded, automatically_reconnect, connect_once +from realtime.client import automatically_reconnect, connect_once from realtime.message import ( AccessTokenMessage, ChannelLeaveMessage, diff --git a/src/storage/src/storage3/exceptions.py b/src/storage/src/storage3/exceptions.py index bed0c69e1..dc8b57fb5 100644 --- a/src/storage/src/storage3/exceptions.py +++ b/src/storage/src/storage3/exceptions.py @@ -1,18 +1,25 @@ -from typing import override +from __future__ import annotations + +from typing import TYPE_CHECKING from pydantic import BaseModel, TypeAdapter, ValidationError -from pydantic.dataclasses import dataclass -from supabase_utils.http.request import Response +from supabase_utils.errors import SupabaseError +from supabase_utils.http.errors import SupabaseAPIError + +if TYPE_CHECKING: + from supabase_utils.http.request import Response + +class StorageException(SupabaseError): + """Raised when a storage operation fails. -class StorageException(Exception): - """Error raised when an operation on the storage API fails.""" + A plain `StorageException` is a failure the client raised on its own. A + failure the storage service reported is a `StorageApiError`. + """ class VectorBucketException(StorageException): - def __init__(self, message: str) -> None: - super().__init__(message) - self.message = message + """Raised when a vector bucket operation is given invalid input.""" class StorageApiErrorMessage(BaseModel): @@ -28,19 +35,19 @@ class StorageApiErrorMessage(BaseModel): VectorBucketErrorMessage = StorageApiErrorMessage -@dataclass -class StorageApiError(StorageException): - message: str - code: str - status: int | str - - @override - def __repr__(self) -> str: - return str(self) +class StorageApiError(StorageException, SupabaseAPIError): + """Raised when the storage service answered a request with an error. + `code` is the error code of the service, such as `NoSuchKey`.""" - @override - def __str__(self) -> str: - return f"StorageApiError(message='{self.message}', code={self.code}, status='{self.status}')" + def __init__( + self, + message: str, + *, + status_code: int, + code: str, + response: Response | None = None, + ) -> None: + super().__init__(message, status_code=status_code, code=code, response=response) StorageApiErrorParser = TypeAdapter(StorageApiErrorMessage) @@ -53,12 +60,16 @@ def parse_api_error(response: Response) -> StorageApiError: body = response.content.decode("utf-8", errors="replace") message = f"Unable to parse error message: {body}" return StorageApiError( - message=message, code="InternalError", status=response.status + message, + status_code=response.status, + code="InternalError", + response=response, ) return StorageApiError( - message=parsed.message, + parsed.message, + status_code=response.status, code=parsed.code or parsed.error, - status=response.status, + response=response, ) diff --git a/src/storage/tests/_async/test_client.py b/src/storage/tests/_async/test_client.py index 13e82ba51..0eccac6cc 100644 --- a/src/storage/tests/_async/test_client.py +++ b/src/storage/tests/_async/test_client.py @@ -553,7 +553,7 @@ async def test_client_info_with_error( err = exc_info.value assert err.message == "File not found" assert err.code == "Custom error message" - assert err.status == 404 + assert err.status_code == 404 async def test_client_exists( diff --git a/src/storage/tests/_sync/test_client.py b/src/storage/tests/_sync/test_client.py index e17c9497c..e6df00ac8 100644 --- a/src/storage/tests/_sync/test_client.py +++ b/src/storage/tests/_sync/test_client.py @@ -548,7 +548,7 @@ def test_client_info_with_error( err = exc_info.value assert err.message == "File not found" assert err.code == "Custom error message" - assert err.status == 404 + assert err.status_code == 404 def test_client_exists( diff --git a/src/storage/tests/test_exceptions.py b/src/storage/tests/test_exceptions.py index bdde78401..06318e7b0 100644 --- a/src/storage/tests/test_exceptions.py +++ b/src/storage/tests/test_exceptions.py @@ -1,9 +1,18 @@ +import pickle + import pytest +from supabase_utils.errors import SupabaseError +from supabase_utils.http.errors import SupabaseAPIError from supabase_utils.http.headers import Headers from supabase_utils.http.request import Request, Response from yarl import URL -from storage3.exceptions import StorageApiError, parse_api_error +from storage3.exceptions import ( + StorageApiError, + StorageException, + VectorBucketException, + parse_api_error, +) def _response(content: bytes, status: int = 502) -> Response: @@ -31,7 +40,7 @@ def test_parse_api_error_reads_wire_format() -> None: ) assert err.message == "Object not found" assert err.code == "not_found" - assert err.status == 400 + assert err.status_code == 400 def test_parse_api_error_prefers_explicit_code() -> None: @@ -41,7 +50,7 @@ def test_parse_api_error_prefers_explicit_code() -> None: ) ) assert err.code == "PayloadTooLarge" - assert err.status == 502 + assert err.status_code == 502 @pytest.mark.parametrize( @@ -61,4 +70,34 @@ def test_parse_api_error_falls_back_with_real_status(body: bytes) -> None: err = parse_api_error(_response(body, status=502)) assert isinstance(err, StorageApiError) assert err.code == "InternalError" - assert err.status == 502 + assert err.status_code == 502 + + +def test_storage_errors_inherit_the_shared_roots() -> None: + assert issubclass(StorageException, SupabaseError) + assert not issubclass(StorageException, SupabaseAPIError) + assert issubclass(VectorBucketException, StorageException) + assert issubclass(StorageApiError, StorageException) + assert issubclass(StorageApiError, SupabaseAPIError) + + +def test_parse_api_error_keeps_the_response() -> None: + response = _response(b'{"statusCode":"404","error":"not_found","message":"gone"}') + err = parse_api_error(response) + assert str(err) == "gone" + assert err.response is response + + +def test_vector_bucket_exception_message() -> None: + err = VectorBucketException("Keys batch size must be between 1 and 500.") + assert str(err) == err.message == "Keys batch size must be between 1 and 500." + assert err.code is None + + +def test_storage_api_error_can_be_pickled() -> None: + err = parse_api_error(_response(b"[]", status=502)) + clone = pickle.loads(pickle.dumps(err)) + assert isinstance(clone, StorageApiError) + assert clone.code == "InternalError" + assert clone.status_code == 502 + assert str(clone) == str(err) diff --git a/src/storage/tests/test_file_api.py b/src/storage/tests/test_file_api.py index 3a18dcedc..cab68896c 100644 --- a/src/storage/tests/test_file_api.py +++ b/src/storage/tests/test_file_api.py @@ -193,14 +193,14 @@ def collect_sync(b: StorageFileApiClient[SyncHttpIO]) -> None: async def test_exists_reraises_unexpected_status(use_async: bool) -> None: with pytest.raises(StorageApiError) as error: await run(use_async, lambda b: b.exists("missing.txt"), 401, b"") - assert error.value.status == 401 + assert error.value.status_code == 401 @use_async async def test_error_with_binary_body_raises_storage_api_error(use_async: bool) -> None: with pytest.raises(StorageApiError) as error: await run(use_async, lambda b: b.download("file.txt"), 502, b"\xff\xfe") - assert error.value.status == 502 + assert error.value.status_code == 502 @use_async diff --git a/src/supabase/README.md b/src/supabase/README.md index 07e3c137e..1cc64b4af 100644 --- a/src/supabase/README.md +++ b/src/supabase/README.md @@ -145,7 +145,7 @@ def test_func(): resp = supabase.functions.invoke("hello-world", body={}) return resp except (FunctionsRelayError, FunctionsHttpError) as exception: - print(exception.status, exception.message) + print(exception.status_code, exception.message) ``` ### Download a file from Storage @@ -191,6 +191,52 @@ new_file_path: str = "important/revenue.png" data = supabase.storage.from_(bucket_name).move(old_file_path, new_file_path) ``` +## Error handling + +Every exception the client raises inherits from `SupabaseError`, so one clause catches them all: + +```python +from supabase import SupabaseAPIError, SupabaseError, SupabaseTransportError + +try: + data = supabase.table("countries").select("*").execute() +except SupabaseAPIError as error: + # A service answered with an error. + print(error.status_code, error.code, error.message) +except SupabaseTransportError as error: + # No response could be read. The httpx or aiohttp exception is the cause. + print(error.__cause__) +except SupabaseError as error: + # The client failed on its own, such as a missing session. + print(error.message) +``` + +Every error has a `message`, also returned by `str(error)`, and a `code` that is the identifier of the failure when the service or the client named it, such as `weak_password` or `PGRST116`. A `SupabaseAPIError` adds the `status_code` and the `response` of the failed request, whose headers carry the `sb-request-id` to quote when asking for support. A `SupabaseTransportError` adds the `request` that was sent. It is raised when the connection failed, the request timed out, or the HTTP client gave up, as on a redirect loop. The outcome of such a request is unknown, since it may have reached the service. + +``` +SupabaseError +├── SupabaseAPIError A service answered with an error. +│ ├── AuthApiError ├── AuthRetryableError, AuthWeakPasswordError +│ ├── AuthUnknownError The auth error body could not be parsed. +│ ├── PostgrestAPIError message, code, hint and details of the PostgREST error. +│ ├── StorageApiError +│ ├── FunctionsHttpError +│ └── FunctionsRelayError +├── SupabaseTransportError No response could be read. The HTTP client's exception is `__cause__`. +│ └── RequestTimeoutError Also a built-in `TimeoutError`. +├── AuthError Root of the auth errors. Raised by the auth client itself as +│ AuthSessionMissingError, AuthInvalidCredentialsError, +│ AuthInvalidJwtError, AuthImplicitGrantRedirectError, +│ UserDoesNotExistError +├── StorageException Root of the storage errors: VectorBucketException +├── FunctionsError Root of the functions errors. +├── RealtimeError Root of the realtime errors: NotConnectedError, +│ AuthorizationError, MaxRetriesExceeded +└── SupabaseException The client was created with an invalid URL or key. +``` + +The response errors inherit both from the root of their package and from `SupabaseAPIError`, so `except AuthApiError` and `except AuthError` keep working. Arguments the client rejects before sending a request raise the built-in `ValueError` or `TypeError`, as they do everywhere in Python, except for a vector batch of the wrong size, which raises `VectorBucketException`. A lost realtime connection is reported as the `websockets.ConnectionClosed` or built-in `TimeoutError` that failed it, not as a `SupabaseError`. + ## Important: Proper Client Shutdown To ensure the Supabase client terminates correctly and to prevent resource leaks, you **must** explicitly call: diff --git a/src/supabase/src/supabase/__init__.py b/src/supabase/src/supabase/__init__.py index e878d8830..f8248ba0f 100644 --- a/src/supabase/src/supabase/__init__.py +++ b/src/supabase/src/supabase/__init__.py @@ -1,6 +1,11 @@ from postgrest import APIError as PostgrestAPIError from postgrest import APIResponse as PostgrestAPIResponse -from realtime import AuthorizationError, NotConnectedError +from realtime import ( + AuthorizationError, + MaxRetriesExceeded, + NotConnectedError, + RealtimeError, +) from storage3 import StorageApiError, StorageException, VectorBucketException from supabase_auth import ( AuthApiError, @@ -12,7 +17,6 @@ AuthSessionMissingError, AuthUnknownError, AuthWeakPasswordError, - CustomAuthError, UserDoesNotExistError, ) from supabase_functions import ( @@ -20,7 +24,12 @@ FunctionsHttpError, FunctionsRelayError, ) -from supabase_utils.http.errors import RequestTimeoutError +from supabase_utils.errors import SupabaseError +from supabase_utils.http.errors import ( + RequestTimeoutError, + SupabaseAPIError, + SupabaseTransportError, +) from .client import AsyncClient, Client, SupabaseException from .types import ( @@ -48,21 +57,25 @@ "AuthWeakPasswordError", "AuthorizationError", "Client", - "CustomAuthError", "FunctionsClientOptions", "FunctionsError", "FunctionsHttpError", "FunctionsRelayError", + "MaxRetriesExceeded", "NotConnectedError", "PostgrestAPIError", "PostgrestAPIResponse", "PostgrestClientOptions", "RealtimeClientOptions", + "RealtimeError", "RequestTimeoutError", "StorageApiError", "StorageClientOptions", "StorageException", + "SupabaseAPIError", + "SupabaseError", "SupabaseException", + "SupabaseTransportError", "UserDoesNotExistError", "VectorBucketException", "__version__", diff --git a/src/supabase/src/supabase/client.py b/src/supabase/src/supabase/client.py index 0c6df9f7e..f38815413 100644 --- a/src/supabase/src/supabase/client.py +++ b/src/supabase/src/supabase/client.py @@ -9,7 +9,13 @@ from postgrest import APIError as PostgrestAPIError from postgrest import APIResponse as PostgrestAPIResponse from postgrest import AsyncPostgrestClient, SyncPostgrestClient -from realtime import AuthorizationError, NotConnectedError, connect_once +from realtime import ( + AuthorizationError, + MaxRetriesExceeded, + NotConnectedError, + RealtimeError, + connect_once, +) from storage3 import ( AsyncStorageClient, StorageApiError, @@ -29,7 +35,6 @@ AuthSessionMissingError, AuthUnknownError, AuthWeakPasswordError, - CustomAuthError, SyncSupabaseAuthClient, SyncSupportedStorage, UserDoesNotExistError, @@ -41,7 +46,12 @@ FunctionsRelayError, SyncFunctionsClient, ) -from supabase_utils.http.errors import RequestTimeoutError +from supabase_utils.errors import SupabaseError +from supabase_utils.http.errors import ( + RequestTimeoutError, + SupabaseAPIError, + SupabaseTransportError, +) from supabase_utils.http.io import ( AsyncHttpIO, AsyncHttpSession, @@ -92,18 +102,22 @@ "AuthWeakPasswordError", "AuthorizationError", "Client", - "CustomAuthError", "FunctionsError", "FunctionsHttpError", "FunctionsRelayError", + "MaxRetriesExceeded", "NotConnectedError", "PostgrestAPIError", "PostgrestAPIResponse", + "RealtimeError", "RequestTimeoutError", "StorageApiError", "StorageException", + "SupabaseAPIError", "SupabaseClient", + "SupabaseError", "SupabaseException", + "SupabaseTransportError", "UserDoesNotExistError", "VectorBucketException", "__version__", @@ -121,13 +135,9 @@ } -class SupabaseException(Exception): +class SupabaseException(SupabaseError): """Raised when the client is created with a missing or invalid URL or key.""" - def __init__(self, message: str) -> None: - self.message = message - super().__init__(self.message) - def _find_authorization(headers: Mapping[str, str]) -> str | None: return next( diff --git a/src/supabase/tests/test_exports.py b/src/supabase/tests/test_exports.py index 29060c2c8..81fdc3c04 100644 --- a/src/supabase/tests/test_exports.py +++ b/src/supabase/tests/test_exports.py @@ -7,7 +7,12 @@ import storage3 import supabase_auth import supabase_functions -from supabase_utils.http.errors import RequestTimeoutError +from supabase_utils.errors import SupabaseError +from supabase_utils.http.errors import ( + RequestTimeoutError, + SupabaseAPIError, + SupabaseTransportError, +) import supabase import supabase.client @@ -49,7 +54,6 @@ def test_package_declares_all(name: str) -> None: "AuthSessionMissingError", "AuthUnknownError", "AuthWeakPasswordError", - "CustomAuthError", "UserDoesNotExistError", ], ), @@ -61,7 +65,15 @@ def test_package_declares_all(name: str) -> None: supabase_functions, ["FunctionsError", "FunctionsHttpError", "FunctionsRelayError"], ), - (realtime, ["AuthorizationError", "NotConnectedError"]), + ( + realtime, + [ + "AuthorizationError", + "MaxRetriesExceeded", + "NotConnectedError", + "RealtimeError", + ], + ), ], ) def test_errors_are_exported_from_package_and_supabase( @@ -79,6 +91,26 @@ def test_postgrest_error_is_exported_from_supabase() -> None: assert supabase.PostgrestAPIError is postgrest.APIError -def test_request_timeout_error_is_exported_from_supabase() -> None: - assert supabase.RequestTimeoutError is RequestTimeoutError - assert supabase.client.RequestTimeoutError is RequestTimeoutError +@pytest.mark.parametrize( + ("name", "error"), + [ + ("RequestTimeoutError", RequestTimeoutError), + ("SupabaseAPIError", SupabaseAPIError), + ("SupabaseError", SupabaseError), + ("SupabaseTransportError", SupabaseTransportError), + ], +) +def test_shared_errors_are_exported_from_supabase( + name: str, error: type[SupabaseError] +) -> None: + assert name in supabase.__all__ + assert getattr(supabase, name) is error + assert name in supabase.client.__all__ + assert getattr(supabase.client, name) is error + + +def test_every_exported_error_is_a_supabase_error() -> None: + for name in supabase.__all__: + symbol = getattr(supabase, name) + if isinstance(symbol, type) and issubclass(symbol, BaseException): + assert issubclass(symbol, SupabaseError), name diff --git a/src/utils/README.md b/src/utils/README.md index c8b6cd8dd..d148ba283 100644 --- a/src/utils/README.md +++ b/src/utils/README.md @@ -87,7 +87,8 @@ The main modules are: | `supabase_utils.http.headers` | `Headers`, an immutable, case insensitive multi map of header values. | | `supabase_utils.http.query` | `URLQuery`, an immutable multi map of query parameters. | | `supabase_utils.http.io` | The `HttpSession` and `AsyncHttpSession` protocols, the `SyncHttpIO` and `AsyncHttpIO` executors and `handle_http_io`. | -| `supabase_utils.http.errors` | `RequestTimeoutError`, raised by an adapter when a request times out. | +| `supabase_utils.errors` | `SupabaseError`, the base class of every exception the packages raise. | +| `supabase_utils.http.errors` | `SupabaseAPIError` for error responses, and `SupabaseTransportError` and its subclass `RequestTimeoutError`, raised by an adapter. | | `supabase_utils.http.redirects` | `keeps_credentials` and `CREDENTIAL_HEADERS`, for adapters that follow redirects. | | `supabase_utils.http.adapters` | The adapters for httpx and aiohttp. | @@ -109,7 +110,7 @@ An adapter connects another HTTP library. It implements one of two protocols fro | `delay` | `float \| None` | Seconds to wait before sending. The executor waits, not the adapter. | | `timeout` | `float \| None` | Seconds a request may go without progress. `None` leaves it to the client. | -It returns a `Response` with the status code, the body as `bytes`, the response headers and the request it answers. `send` must not raise for error statuses: the packages read `response.status` and raise their own errors. `timeout` limits each step of a request, such as connecting or reading, not the whole request. Raise `RequestTimeoutError` from `supabase_utils.http.errors` for every timeout, whether `timeout` or the client's own limit elapsed, so every adapter reports a timeout the same way. A library without a client-level timeout needs a default in the adapter, or `None` waits forever. Other errors of the transport itself, such as a refused connection, should propagate. +It returns a `Response` with the status code, the body as `bytes`, the response headers and the request it answers. `send` must not raise for error statuses: the packages read `response.status` and raise their own errors. `timeout` limits each step of a request, such as connecting or reading, not the whole request. Raise `RequestTimeoutError` from `supabase_utils.http.errors` for every timeout, whether `timeout` or the client's own limit elapsed, so every adapter reports a timeout the same way. A library without a client-level timeout needs a default in the adapter, or `None` waits forever. Wrap every other error of the transport itself, such as a refused connection, in `SupabaseTransportError` with `raise ... from error`, so that `except SupabaseError` catches it whichever library sends the requests and the original exception stays available as `__cause__`. Do not copy the text of that exception into the message: some libraries quote the full URL, and the URL of a signed upload carries a token. If the library follows redirects, apply the rule from [Using an adapter](#using-an-adapter): drop the headers in `CREDENTIAL_HEADERS` from `supabase_utils.http.redirects` once `keeps_credentials(request.url, target)` is false. `target` is the `Location` header resolved against the URL of the response that sent it, as in `response_url.join(URL(location))`, since a relative location has no host of its own. The simplest way to stay safe is to not follow redirects at all. @@ -121,7 +122,7 @@ A minimal adapter for the `requests` library: from types import TracebackType import requests -from supabase_utils.http.errors import RequestTimeoutError +from supabase_utils.http.errors import RequestTimeoutError, SupabaseTransportError from supabase_utils.http.headers import Headers from supabase_utils.http.request import Request, Response from urllib3.exceptions import MaxRetryError, ReadTimeoutError @@ -154,7 +155,9 @@ class RequestsSession: except requests.ConnectionError as error: if is_read_timeout(error): raise RequestTimeoutError(request) from error - raise + raise SupabaseTransportError(request) from error + except requests.RequestException as error: + raise SupabaseTransportError(request) from error return Response( status=response.status_code, content=content, @@ -174,7 +177,7 @@ class RequestsSession: self.session.close() ``` -`dict(request.headers)` joins the values of a repeated header with `, `. Pass `request.headers.iter_items()` instead if the library accepts a list of pairs, as httpx does. `requests` has no client-level timeout, so the example falls back to 60 seconds. It raises `requests.Timeout` for some read timeouts, but reports others as `ConnectionError` around a `ReadTimeoutError`, sometimes inside a `MaxRetryError`, so `is_read_timeout` translates those too. Reading `response.content` inside the `try` block covers a session that streams responses. `allow_redirects=False` keeps it out of the redirect rule above. +`dict(request.headers)` joins the values of a repeated header with `, `. Pass `request.headers.iter_items()` instead if the library accepts a list of pairs, as httpx does. `requests` has no client-level timeout, so the example falls back to 60 seconds. It raises `requests.Timeout` for some read timeouts, but reports others as `ConnectionError` around a `ReadTimeoutError`, sometimes inside a `MaxRetryError`, so `is_read_timeout` translates those too. Reading `response.content` inside the `try` block covers a session that streams responses, and the remaining `RequestException`s become `SupabaseTransportError`s. `allow_redirects=False` keeps it out of the redirect rule above. The adapters in [`src/supabase_utils/http/adapters`](src/supabase_utils/http/adapters) are complete examples. diff --git a/src/utils/src/supabase_utils/errors.py b/src/utils/src/supabase_utils/errors.py new file mode 100644 index 000000000..0f85224ad --- /dev/null +++ b/src/utils/src/supabase_utils/errors.py @@ -0,0 +1,49 @@ +from __future__ import annotations + +from typing import Any + + +def _rebuild( + cls: type[SupabaseError], args: tuple[Any, ...], state: dict[str, Any] +) -> SupabaseError: + error = cls.__new__(cls) + error.args = args + error.__dict__.update(state) + return error + + +class SupabaseError(Exception): + """Base class of every exception the supabase packages raise. + + A plain `SupabaseError` is a failure a client raised on its own, without + or before a request, such as a missing session or an invalid URL. A + failure a service answered with is a `SupabaseAPIError`, and a request + that failed before a response could be read is a `SupabaseTransportError`, + both in + `supabase_utils.http.errors`. + + The roots of the packages all inherit from it: `AuthError`, + `postgrest.APIError`, `StorageException`, `FunctionsError`, + `RealtimeError` and `SupabaseException`. + + ```python + try: + client.table("countries").select("*").execute() + except SupabaseError as error: + print(error.message) + ``` + """ + + def __init__(self, message: str, *, code: str | None = None) -> None: + super().__init__(message) + self.message = message + """Human readable description of the failure, also returned by `str()`.""" + self.code = code + """Identifier of the failure, such as `weak_password` (auth), `PGRST116` + (postgrest) or `NoSuchKey` (storage). None when neither the service nor + the client named it.""" + + def __reduce__(self) -> tuple[Any, ...]: + # The constructors of the subclasses take different arguments than the + # ones stored in `args`, so rebuild from the instance state instead. + return (_rebuild, (type(self), self.args, self.__dict__)) diff --git a/src/utils/src/supabase_utils/http/adapters/aiohttp.py b/src/utils/src/supabase_utils/http/adapters/aiohttp.py index c4db906aa..5a7321a29 100644 --- a/src/utils/src/supabase_utils/http/adapters/aiohttp.py +++ b/src/utils/src/supabase_utils/http/adapters/aiohttp.py @@ -1,6 +1,7 @@ from types import TracebackType from aiohttp import ( + ClientError, ClientHandlerType, ClientMiddlewareType, ClientRequest, @@ -10,7 +11,7 @@ from aiohttp import ClientResponse as AioResponse from yarl import URL -from ..errors import RequestTimeoutError +from ..errors import RequestTimeoutError, SupabaseTransportError from ..headers import Headers from ..redirects import CREDENTIAL_HEADERS, keeps_credentials from ..request import Request, Response @@ -65,6 +66,9 @@ async def send(self, request: Request) -> Response: data=request.content, headers=dict(request.headers), timeout=self._timeout(request.timeout), + # The packages read the status themselves, so an error status + # must come back as a response even on a session that raises. + raise_for_status=False, middlewares=( # Per request middlewares replace the session ones, so keep those. *self.client._middlewares, @@ -74,6 +78,8 @@ async def send(self, request: Request) -> Response: return await to_supabase_response(request, response) except TimeoutError as error: raise RequestTimeoutError(request) from error + except ClientError as error: + raise SupabaseTransportError(request) from error async def __aenter__(self) -> "AsyncAiohttpSession": return self diff --git a/src/utils/src/supabase_utils/http/adapters/httpx.py b/src/utils/src/supabase_utils/http/adapters/httpx.py index 7d76fec96..a1aef03e7 100644 --- a/src/utils/src/supabase_utils/http/adapters/httpx.py +++ b/src/utils/src/supabase_utils/http/adapters/httpx.py @@ -1,11 +1,19 @@ from types import TracebackType -from httpx import AsyncClient, Auth, Client, Timeout, TimeoutException, TooManyRedirects +from httpx import ( + AsyncClient, + Auth, + Client, + RequestError, + Timeout, + TimeoutException, + TooManyRedirects, +) from httpx import Request as HttpxRequest from httpx import Response as HttpxResponse from yarl import URL -from ..errors import RequestTimeoutError +from ..errors import RequestTimeoutError, SupabaseTransportError from ..headers import Headers from ..redirects import CREDENTIAL_HEADERS, keeps_credentials from ..request import Request, Response @@ -58,6 +66,8 @@ def send(self, request: Request) -> Response: return self._send(request) except TimeoutException as error: raise RequestTimeoutError(request) from error + except RequestError as error: + raise SupabaseTransportError(request) from error def _send(self, request: Request) -> Response: httpx_request = to_httpx_request(request) @@ -99,6 +109,8 @@ async def send(self, request: Request) -> Response: return await self._send(request) except TimeoutException as error: raise RequestTimeoutError(request) from error + except RequestError as error: + raise SupabaseTransportError(request) from error async def _send(self, request: Request) -> Response: httpx_request = to_httpx_request(request) diff --git a/src/utils/src/supabase_utils/http/errors.py b/src/utils/src/supabase_utils/http/errors.py index 6c6c542ce..8ec3277f9 100644 --- a/src/utils/src/supabase_utils/http/errors.py +++ b/src/utils/src/supabase_utils/http/errors.py @@ -1,14 +1,70 @@ -from typing import Any +from __future__ import annotations -from .request import Request +from typing import TYPE_CHECKING +from ..errors import SupabaseError -class RequestTimeoutError(TimeoutError): - """Raised when a request to a Supabase service times out.""" +if TYPE_CHECKING: + from .request import Request, Response - def __init__(self, request: Request) -> None: + +class SupabaseAPIError(SupabaseError): + """Raised when a Supabase service answered a request with an error. + + Catch it to handle a failure any service reported: + + ```python + try: + client.table("countries").select("*").execute() + except SupabaseAPIError as error: + print(error.status_code, error.message) + ``` + """ + + def __init__( + self, + message: str, + *, + status_code: int, + code: str | None = None, + response: Response | None = None, + ) -> None: + super().__init__(message, code=code) + self.status_code = status_code + """HTTP status code of the response that caused the error.""" + self.response = response + """The response that caused the error. Its `content` is the body as + the service sent it, and its `headers` carry the `sb-request-id` to + quote when asking for support. None when the error was built without + a response, as a client-side check does.""" + + +class SupabaseTransportError(SupabaseError): + """Raised when a request to a Supabase service failed before a response + could be read, because the connection failed, the request timed out, or + the HTTP client gave up, as on a redirect loop. + + The exception of the HTTP client is chained as `__cause__`. Its text is + not copied into the message, since it can quote the URL of the request + with the token of a signed URL. The request may still have reached the + service, so the outcome of an operation that is not idempotent is unknown. + + ```python + try: + client.table("countries").select("*").execute() + except SupabaseTransportError as error: + print(f"No response: {error.__cause__!r}") + ``` + """ + + def __init__(self, request: Request, reason: str = "failed") -> None: self.request = request - super().__init__(f"{request.method} {request.url.with_query(None)} timed out") + """The request that was sent.""" + super().__init__(f"{request.method} {request.url.with_query(None)} {reason}") + - def __reduce__(self) -> tuple[Any, ...]: - return (type(self), (self.request,), self.__dict__) +class RequestTimeoutError(SupabaseTransportError, TimeoutError): + """Raised when a request to a Supabase service times out.""" + + def __init__(self, request: Request) -> None: + super().__init__(request, "timed out") diff --git a/src/utils/tests/test_aiohttp_adapter.py b/src/utils/tests/test_aiohttp_adapter.py index bae76029d..4718bf6b1 100644 --- a/src/utils/tests/test_aiohttp_adapter.py +++ b/src/utils/tests/test_aiohttp_adapter.py @@ -6,7 +6,7 @@ from aiohttp import web from aiohttp.test_utils import TestServer from supabase_utils.http.adapters.aiohttp import AsyncAiohttpSession -from supabase_utils.http.errors import RequestTimeoutError +from supabase_utils.http.errors import RequestTimeoutError, SupabaseTransportError from supabase_utils.http.headers import Headers from supabase_utils.http.io import AsyncHttpIO, HttpMethod from supabase_utils.http.query import URLQuery @@ -247,6 +247,31 @@ async def test_session_timeout_raises_request_timeout_error( ) +async def test_error_status_is_returned_on_a_session_that_raises( + server: TestServer, +) -> None: + client = aiohttp.ClientSession(raise_for_status=True) + async with AsyncAiohttpSession(client) as session: + response = await AsyncHttpIO(session).communicate( + base_url(server), Headers.empty(), get_missing() + ) + assert response.status == 404 + assert response.content == b"missing" + + +async def test_connection_failure_raises_transport_error(server: TestServer) -> None: + unreachable = server.make_url("/api").with_port(1) + async with AsyncAiohttpSession(aiohttp.ClientSession()) as session: + with pytest.raises(SupabaseTransportError) as error: + await AsyncHttpIO(session).communicate( + unreachable, Headers.empty(), get_missing() + ) + assert not isinstance(error.value, RequestTimeoutError) + assert isinstance(error.value.__cause__, aiohttp.ClientConnectorError) + assert str(error.value) == f"GET {unreachable}/missing failed" + assert error.value.request.method == "GET" + + async def test_request_timeout_overrides_session_read_timeout( server: TestServer, ) -> None: diff --git a/src/utils/tests/test_errors.py b/src/utils/tests/test_errors.py new file mode 100644 index 000000000..cf00263c8 --- /dev/null +++ b/src/utils/tests/test_errors.py @@ -0,0 +1,120 @@ +import copy +import pickle + +import pytest +from supabase_utils.errors import SupabaseError +from supabase_utils.http.errors import ( + RequestTimeoutError, + SupabaseAPIError, + SupabaseTransportError, +) +from supabase_utils.http.headers import Headers +from supabase_utils.http.request import Request, Response +from yarl import URL + + +def make_request() -> Request: + return Request( + url=URL("https://example.com/rest/v1/items?select=id"), + method="GET", + headers=Headers.empty(), + content=None, + delay=None, + ) + + +def make_response(status: int = 404) -> Response: + return Response( + headers=Headers.from_mapping({"sb-request-id": "req-1"}), + content=b'{"message":"missing"}', + status=status, + request=make_request(), + ) + + +class CustomError(SupabaseError): + def __init__(self, value: int) -> None: + super().__init__(f"custom {value}", code="custom") + self.value = value + + +def test_supabase_error_message_and_code() -> None: + error = SupabaseError("boom") + assert isinstance(error, Exception) + assert str(error) == "boom" + assert error.message == "boom" + assert error.code is None + assert SupabaseError("boom", code="PGRST116").code == "PGRST116" + + +def test_api_error_carries_status_code_and_response() -> None: + response = make_response() + error = SupabaseAPIError( + "missing", status_code=404, code="not_found", response=response + ) + assert isinstance(error, SupabaseError) + assert str(error) == "missing" + assert error.status_code == 404 + assert error.code == "not_found" + assert error.response is response + assert error.response.headers.get("sb-request-id") == "req-1" + assert SupabaseAPIError("x", status_code=500).response is None + + +def test_transport_error_describes_the_request_without_the_query() -> None: + error = SupabaseTransportError(make_request()) + assert isinstance(error, SupabaseError) + assert not isinstance(error, SupabaseAPIError) + assert str(error) == "GET https://example.com/rest/v1/items failed" + assert error.request.method == "GET" + detailed = SupabaseTransportError(make_request(), "failed: connection refused") + assert str(detailed) == ( + "GET https://example.com/rest/v1/items failed: connection refused" + ) + + +def test_request_timeout_error_is_a_transport_error_and_a_timeout() -> None: + error = RequestTimeoutError(make_request()) + assert isinstance(error, SupabaseTransportError) + assert isinstance(error, TimeoutError) + assert str(error) == "GET https://example.com/rest/v1/items timed out" + + +def test_transport_error_can_be_caught_as_supabase_error() -> None: + with pytest.raises(SupabaseError): + raise RequestTimeoutError(make_request()) + + +@pytest.mark.parametrize( + "error", + [ + SupabaseError("boom", code="c"), + SupabaseAPIError( + "missing", status_code=404, code="n", response=make_response() + ), + SupabaseTransportError(make_request(), "failed: refused"), + RequestTimeoutError(make_request()), + CustomError(7), + ], +) +def test_errors_can_be_pickled_and_copied(error: SupabaseError) -> None: + for clone in (pickle.loads(pickle.dumps(error)), copy.copy(error)): + assert type(clone) is type(error) + assert str(clone) == str(error) + assert clone.args == error.args + assert clone.message == error.message + assert clone.code == error.code + for name, value in vars(error).items(): + if isinstance(value, (Request, Response)): + assert str(getattr(clone, name)) == str(value) + else: + assert getattr(clone, name) == value + + +def test_pickled_api_error_keeps_the_response() -> None: + error = SupabaseAPIError("missing", status_code=404, response=make_response()) + clone = pickle.loads(pickle.dumps(error)) + assert clone.status_code == 404 + assert clone.response is not None + assert clone.response.status == 404 + assert clone.response.content == b'{"message":"missing"}' diff --git a/src/utils/tests/test_httpx_adapter.py b/src/utils/tests/test_httpx_adapter.py index 569a2edf1..196a815a9 100644 --- a/src/utils/tests/test_httpx_adapter.py +++ b/src/utils/tests/test_httpx_adapter.py @@ -9,7 +9,7 @@ to_httpx_request, to_supabase_response, ) -from supabase_utils.http.errors import RequestTimeoutError +from supabase_utils.http.errors import RequestTimeoutError, SupabaseTransportError from supabase_utils.http.headers import Headers from supabase_utils.http.io import AsyncHttpIO, HttpMethod, SyncHttpIO from supabase_utils.http.query import URLQuery @@ -242,8 +242,12 @@ def handler(request: httpx.Request) -> httpx.Response: follow_redirects=True, max_redirects=2, ) - with HttpxSession(client) as session, pytest.raises(httpx.TooManyRedirects): + with ( + HttpxSession(client) as session, + pytest.raises(SupabaseTransportError) as error, + ): session.send(make_credential_request()) + assert isinstance(error.value.__cause__, httpx.TooManyRedirects) async def test_async_session_respects_max_redirects() -> None: @@ -259,8 +263,9 @@ def handler(request: httpx.Request) -> httpx.Response: max_redirects=2, ) async with AsyncHttpxSession(client) as session: - with pytest.raises(httpx.TooManyRedirects): + with pytest.raises(SupabaseTransportError) as error: await session.send(make_credential_request()) + assert isinstance(error.value.__cause__, httpx.TooManyRedirects) assert len(sent) == 3 @@ -445,3 +450,30 @@ def test_request_timeout_error_can_be_pickled() -> None: assert str(copy) == str(error) assert copy.request.url == error.request.url assert copy.request.method == error.request.method + + +def refuse(request: httpx.Request) -> httpx.Response: + raise httpx.ConnectError("[Errno 61] Connection refused", request=request) + + +def test_sync_session_wraps_transport_errors() -> None: + client = httpx.Client(transport=httpx.MockTransport(refuse)) + with ( + HttpxSession(client) as session, + pytest.raises(SupabaseTransportError) as error, + ): + SyncHttpIO(session).communicate(BASE_URL, Headers.empty(), get_items()) + assert not isinstance(error.value, RequestTimeoutError) + assert isinstance(error.value.__cause__, httpx.ConnectError) + assert str(error.value) == "GET https://example.com/api/items failed" + assert error.value.request.method == "GET" + + +async def test_async_session_wraps_transport_errors() -> None: + client = httpx.AsyncClient(transport=httpx.MockTransport(refuse)) + async with AsyncHttpxSession(client) as session: + with pytest.raises(SupabaseTransportError) as error: + await AsyncHttpIO(session).communicate( + BASE_URL, Headers.empty(), get_items() + ) + assert isinstance(error.value.__cause__, httpx.ConnectError)