Skip to content
Merged
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
38 changes: 38 additions & 0 deletions src/triggerdev/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,41 @@
"""The first fully typed async Python SDK for the Trigger.dev management API."""

from triggerdev._exceptions import (
APIConnectionError,
APIError,
APIStatusError,
APITimeoutError,
AuthenticationError,
BadRequestError,
ConflictError,
ContentTooLargeError,
HTTPNotImplementedError,
InternalServerError,
NotFoundError,
PermissionDeniedError,
RateLimitError,
ServiceUnavailableError,
TriggerDevError,
UnprocessableEntityError,
)

__all__ = [
"APIConnectionError",
"APIError",
"APIStatusError",
"APITimeoutError",
"AuthenticationError",
"BadRequestError",
"ConflictError",
"ContentTooLargeError",
"HTTPNotImplementedError",
"InternalServerError",
"NotFoundError",
"PermissionDeniedError",
"RateLimitError",
"ServiceUnavailableError",
"TriggerDevError",
"UnprocessableEntityError",
]

__version__ = "0.0.0"
155 changes: 155 additions & 0 deletions src/triggerdev/_exceptions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
"""Trigger.dev SDK exceptions."""

from __future__ import annotations

from typing import TYPE_CHECKING

if TYPE_CHECKING:
import httpx


class TriggerDevError(Exception):
"""Base for all Trigger.dev SDK errors."""

message: str

def __init__(self, message: str) -> None:
super().__init__(message)
self.message = message


class APIError(TriggerDevError):
"""An error from the Trigger.dev API."""

request: httpx.Request
body: object | None

def __init__(
self,
message: str,
*,
request: httpx.Request,
body: object | None,
) -> None:
super().__init__(message)
self.request = request
self.body = body


class APIStatusError(APIError):
"""An HTTP error response from the API."""

response: httpx.Response
status_code: int

def __init__(
self,
message: str,
*,
response: httpx.Response,
body: object | None,
) -> None:
super().__init__(
message,
request=response.request,
body=body,
)
self.response = response
self.status_code = response.status_code

def __str__(self) -> str:
return f"{self.status_code} {self.message}"


class BadRequestError(APIStatusError):
"""The request was malformed or contained invalid parameters."""


class AuthenticationError(APIStatusError):
"""The API key is missing or invalid."""


class PermissionDeniedError(APIStatusError):
"""The API key lacks permission for this action."""


class NotFoundError(APIStatusError):
"""The requested resource does not exist."""


class ConflictError(APIStatusError):
"""The request conflicts with the current resource state."""


class ContentTooLargeError(APIStatusError):
"""The request payload exceeds the size limit."""


class UnprocessableEntityError(APIStatusError):
"""The request was well-formed but contained semantic errors."""


class RateLimitError(APIStatusError):
"""Too many requests or concurrent operations."""

@property
def retry_after(self) -> float | None:
"""Seconds to wait before retrying, or None if not specified."""
header = self.response.headers.get("retry-after")
if header is None:
return None
try:
return float(header)
except ValueError:
return None


class InternalServerError(APIStatusError):
"""The API encountered an internal error."""


class HTTPNotImplementedError(InternalServerError):
"""The requested functionality is not yet available."""


class ServiceUnavailableError(InternalServerError):
"""The API is temporarily unavailable."""


class APIConnectionError(APIError):
"""Failed to connect to the API."""

def __init__(self, *, request: httpx.Request) -> None:
super().__init__(
"Connection error.",
request=request,
body=None,
)


class APITimeoutError(APIConnectionError):
"""The request timed out."""

def __init__(self, *, request: httpx.Request) -> None:
super().__init__(request=request)
self.message = "Request timed out."


__all__ = [
"APIConnectionError",
"APIError",
"APIStatusError",
"APITimeoutError",
"AuthenticationError",
"BadRequestError",
"ConflictError",
"ContentTooLargeError",
"HTTPNotImplementedError",
"InternalServerError",
"NotFoundError",
"PermissionDeniedError",
"RateLimitError",
"ServiceUnavailableError",
"TriggerDevError",
"UnprocessableEntityError",
]
192 changes: 192 additions & 0 deletions tests/test_exceptions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,192 @@
"""Tests for the Trigger.dev exception hierarchy."""

from __future__ import annotations

import httpx
import pytest

from triggerdev._exceptions import (
APIConnectionError,
APIError,
APIStatusError,
APITimeoutError,
AuthenticationError,
BadRequestError,
ConflictError,
ContentTooLargeError,
HTTPNotImplementedError,
InternalServerError,
NotFoundError,
PermissionDeniedError,
RateLimitError,
ServiceUnavailableError,
TriggerDevError,
UnprocessableEntityError,
)


def _make_request() -> httpx.Request:
return httpx.Request("GET", "https://api.trigger.dev/api/v1/runs")


def _make_response(status_code: int, headers: dict[str, str] | None = None) -> httpx.Response:
return httpx.Response(
status_code,
request=_make_request(),
headers=headers or {},
)


class TestHierarchy:
def test_root_is_exception(self) -> None:
assert issubclass(TriggerDevError, Exception)

def test_api_error_is_triggerdev_error(self) -> None:
assert issubclass(APIError, TriggerDevError)

def test_status_error_is_api_error(self) -> None:
assert issubclass(APIStatusError, APIError)

def test_connection_error_is_api_error(self) -> None:
assert issubclass(APIConnectionError, APIError)

def test_timeout_error_is_connection_error(self) -> None:
assert issubclass(APITimeoutError, APIConnectionError)

def test_5xx_subclasses(self) -> None:
assert issubclass(HTTPNotImplementedError, InternalServerError)
assert issubclass(ServiceUnavailableError, InternalServerError)

@pytest.mark.parametrize(
("cls", "expected"),
[
(BadRequestError, 400),
(AuthenticationError, 401),
(PermissionDeniedError, 403),
(NotFoundError, 404),
(ConflictError, 409),
(ContentTooLargeError, 413),
(UnprocessableEntityError, 422),
(RateLimitError, 429),
(InternalServerError, 500),
(HTTPNotImplementedError, 501),
(ServiceUnavailableError, 503),
],
)
def test_status_code_pinning(self, cls: type[APIStatusError], expected: int) -> None:
resp = _make_response(expected)
err = cls("test", response=resp, body=None)
assert err.status_code == expected


class TestAttributes:
def test_triggerdev_error_message(self) -> None:
err = TriggerDevError("boom")
assert err.message == "boom"
assert str(err) == "boom"

def test_api_error_attributes(self) -> None:
req = _make_request()
err = APIError("boom", request=req, body={"error": "boom"})
assert err.message == "boom"
assert err.request is req
assert err.body == {"error": "boom"}

def test_status_error_attributes(self) -> None:
resp = _make_response(404)
err = NotFoundError("not found", response=resp, body={"error": "not found"})
assert err.response is resp
assert err.status_code == 404
assert err.request is resp.request
assert err.body == {"error": "not found"}

def test_status_error_str(self) -> None:
resp = _make_response(401)
err = AuthenticationError("Unauthorized", response=resp, body=None)
assert str(err) == "401 Unauthorized"

def test_connection_error_attributes(self) -> None:
req = _make_request()
err = APIConnectionError(request=req)
assert err.request is req
assert err.body is None
assert err.message == "Connection error."

def test_timeout_error_attributes(self) -> None:
req = _make_request()
err = APITimeoutError(request=req)
assert err.request is req
assert err.message == "Request timed out."


class TestRetryAfter:
def test_retry_after_present(self) -> None:
resp = _make_response(429, headers={"retry-after": "30"})
err = RateLimitError("rate limited", response=resp, body=None)
assert err.retry_after == 30.0

def test_retry_after_float(self) -> None:
resp = _make_response(429, headers={"retry-after": "1.5"})
err = RateLimitError("rate limited", response=resp, body=None)
assert err.retry_after == 1.5

def test_retry_after_absent(self) -> None:
resp = _make_response(429)
err = RateLimitError("rate limited", response=resp, body=None)
assert err.retry_after is None

def test_retry_after_non_numeric(self) -> None:
resp = _make_response(429, headers={"retry-after": "Wed, 21 Oct 2015 07:28:00 GMT"})
err = RateLimitError("rate limited", response=resp, body=None)
assert err.retry_after is None


class TestPublicReExports:
def test_all_exceptions_importable_from_package(self) -> None:
import triggerdev

for name in [
"APIConnectionError",
"APIError",
"APIStatusError",
"APITimeoutError",
"AuthenticationError",
"BadRequestError",
"ConflictError",
"ContentTooLargeError",
"HTTPNotImplementedError",
"InternalServerError",
"NotFoundError",
"PermissionDeniedError",
"RateLimitError",
"ServiceUnavailableError",
"TriggerDevError",
"UnprocessableEntityError",
]:
assert hasattr(triggerdev, name), f"{name} not exported from triggerdev"


class TestCatchPatterns:
def test_catch_all_with_root(self) -> None:
resp = _make_response(500)
err = InternalServerError("fail", response=resp, body=None)
with pytest.raises(TriggerDevError):
raise err

def test_catch_status_errors(self) -> None:
resp = _make_response(404)
err = NotFoundError("missing", response=resp, body=None)
with pytest.raises(APIStatusError):
raise err

def test_catch_connection_errors(self) -> None:
req = _make_request()
err = APITimeoutError(request=req)
with pytest.raises(APIConnectionError):
raise err

def test_catch_5xx_with_internal_server_error(self) -> None:
resp = _make_response(503)
err = ServiceUnavailableError("unavailable", response=resp, body=None)
with pytest.raises(InternalServerError):
raise err
Loading