Repository Public
1"""Typed errors. Nothing here ever holds the API key."""2from __future__ import annotations34from typing import Any, Optional567class SPMailError(Exception):8 """An answer of the API with a non-2xx status, or a failure to get an answer (status 0)."""910 def __init__(self, message: str, *, status: int = 0, code: str = "error", details: Any = None,11 request_id: Optional[str] = None, retry_after: Optional[float] = None) -> None:12 super().__init__(message)13 self.message = message14 #: HTTP status; 0 when no answer was received.15 self.status = status16 #: Stable machine code of the API (``from_not_allowed``, ``not_found``... docs/API.md section 15).17 self.code = code18 self.details = details19 #: ``X-Request-Id`` of the answer: quote it when reporting a problem.20 self.request_id = request_id21 #: Seconds announced by ``Retry-After``, when present.22 self.retry_after = retry_after2324 def __str__(self) -> str:25 head = f"{self.status} {self.code}" if self.status else self.code26 tail = f" (request {self.request_id})" if self.request_id else ""27 return f"{head}: {self.message}{tail}"282930class BadRequestError(SPMailError):31 """400 - validation (``invalid_request``, ``header_not_allowed``, ``missing_variables``...)."""323334class AuthenticationError(SPMailError):35 """401 - ``unauthenticated``, ``invalid_api_key``, ``key_revoked``, ``key_expired``."""363738class PermissionDeniedError(SPMailError):39 """403 - ``insufficient_scope``, ``from_not_allowed``, ``external_send_denied``..."""404142class NotFoundError(SPMailError):43 """404 - unknown, or not visible to this key (deliberately indistinguishable)."""444546class ConflictError(SPMailError):47 """409 - ``idempotency_conflict``, ``resync_required``, ``address_taken``, ``not_cancellable``..."""484950class UnprocessableEntityError(SPMailError):51 """422 - reserved: the API currently answers validation failures with 400."""525354class RateLimitError(SPMailError):55 """429 - ``rate_limited`` (see ``retry_after``) or ``daily_send_limit_exceeded``."""565758class ServerError(SPMailError):59 """5xx - ``internal``, ``mail_server_unavailable``, ``mail_server_error``."""606162class ConnectionError(SPMailError): # noqa: A001 - mirrors the TypeScript SDK name63 """No answer: DNS, TCP, TLS (``code == "connection_error"``)."""646566class TimeoutError(SPMailError): # noqa: A00167 """The request, or ``wait_for_delivery``, exceeded its time budget (``code == "timeout"``)."""686970class SignatureVerificationError(SPMailError):71 """A webhook signature that does not verify (``code == "invalid_signature"``)."""7273 def __init__(self, message: str) -> None:74 super().__init__(message, status=0, code="invalid_signature")757677_BY_STATUS = {400: BadRequestError, 401: AuthenticationError, 403: PermissionDeniedError, 404: NotFoundError,78 409: ConflictError, 422: UnprocessableEntityError, 429: RateLimitError}798081def error_from_response(status: int, code: str, message: str, details: Any, request_id: Optional[str],82 retry_after: Optional[float]) -> SPMailError:83 cls = _BY_STATUS.get(status) or (ServerError if status >= 500 else SPMailError)84 return cls(message, status=status, code=code, details=details, request_id=request_id, retry_after=retry_after)85