Debian Codegraph @

src/anthropic/_exceptions.py

raw
1 from __future__ import annotations
2
3 import pathlib
4 from typing import Union, cast
5 from typing_extensions import Literal
6
7 import httpx2
8
9 from ._utils import is_dict
10 from .types.shared.error_type import ErrorType
11
12 __all__ = [
13 "BadRequestError",
14 "AuthenticationError",
15 "PermissionDeniedError",
16 "NotFoundError",
17 "ConflictError",
18 "UnprocessableEntityError",
19 "RateLimitError",
20 "InternalServerError",
21 "RetryableError",
22 "RequestTooLargeError",
23 "ServiceUnavailableError",
24 "OverloadedError",
25 "DeadlineExceededError",
26 "CredentialsError",
27 "IdentityTokenFileError",
28 ]
29
30
31 class AnthropicError(Exception):
32 pass
33
34
35 class APIError(AnthropicError):
36 message: str
37 request: httpx2.Request
38
39 body: object | None
40 """The API response body.
41
42 If the API responded with a valid JSON structure then this property will be the
43 decoded result.
44
45 If it isn't a valid JSON structure then this will be the raw response.
46
47 If there was no response associated with this error then it will be `None`.
48 """
49
50 def __init__(self, message: str, request: httpx2.Request, *, body: object | None) -> None: # noqa: ARG002
51 super().__init__(message)
52 self.request = request
53 self.message = message
54 self.body = body
55
56
57 class APIResponseValidationError(APIError):
58 response: httpx2.Response
59 status_code: int
60
61 def __init__(self, response: httpx2.Response, body: object | None, *, message: str | None = None) -> None:
62 super().__init__(message or "Data returned by API invalid for expected schema.", response.request, body=body)
63 self.response = response
64 self.status_code = response.status_code
65
66
67 class APIWebhookValidationError(APIError):
68 pass
69
70
71 class APIStatusError(APIError):
72 """Raised when an API response has a status code of 4xx or 5xx."""
73
74 response: httpx2.Response
75 status_code: int
76 request_id: str | None
77 type: ErrorType | None
78
79 workspace_id: str | None
80
81 def __init__(self, message: str, *, response: httpx2.Response, body: object | None) -> None:
82 super().__init__(message, response.request, body=body)
83 self.response = response
84 self.status_code = response.status_code
85 self.request_id = response.headers.get("request-id")
86 self.workspace_id = response.headers.get("anthropic-workspace-id")
87
88 self.type = None
89 if is_dict(body):
90 error = body.get("error")
91 if is_dict(error):
92 self.type = cast(Union[ErrorType, None], error.get("type"))
93
94
95 class APIConnectionError(APIError):
96 def __init__(self, *, message: str = "Connection error.", request: httpx2.Request) -> None:
97 super().__init__(message, request, body=None)
98
99
100 class APITimeoutError(APIConnectionError):
101 def __init__(self, request: httpx2.Request) -> None:
102 super().__init__(
103 message="Request timed out or interrupted. This could be due to a network timeout, dropped connection, or request cancellation. See https://docs.anthropic.com/en/api/errors#long-requests for more details.",
104 request=request,
105 )
106
107
108 class RetryableError(AnthropicError):
109 """An error that opts into the SDK's retry policy: raise it (e.g. from
110 middleware) to have the request attempt retried.
111
112 The request is only retried while `max_retries` has not been exhausted;
113 once exhausted the error propagates to the caller as-is.
114 """
115
116
117 class CredentialsError(AnthropicError):
118 """Raised when credentials cannot be loaded from local files, config, or the environment."""
119
120
121 class IdentityTokenFileError(CredentialsError):
122 """Raised when the identity token file does not exist, is empty, or cannot be read.
123
124 `path` is the file the provider tried to read (when known), so callers
125 waiting for a projected token to appear can retry without parsing the message.
126 """
127
128 path: pathlib.Path | None
129
130 def __init__(self, message: str, *, path: pathlib.Path | None = None) -> None:
131 super().__init__(message)
132 self.path = path
133
134
135 class BadRequestError(APIStatusError):
136 status_code: Literal[400] = 400 # pyright: ignore[reportIncompatibleVariableOverride]
137
138
139 class AuthenticationError(APIStatusError):
140 status_code: Literal[401] = 401 # pyright: ignore[reportIncompatibleVariableOverride]
141
142
143 class PermissionDeniedError(APIStatusError):
144 status_code: Literal[403] = 403 # pyright: ignore[reportIncompatibleVariableOverride]
145
146
147 class NotFoundError(APIStatusError):
148 status_code: Literal[404] = 404 # pyright: ignore[reportIncompatibleVariableOverride]
149
150
151 class ConflictError(APIStatusError):
152 status_code: Literal[409] = 409 # pyright: ignore[reportIncompatibleVariableOverride]
153
154
155 class RequestTooLargeError(APIStatusError):
156 status_code: Literal[413] = 413 # pyright: ignore[reportIncompatibleVariableOverride]
157
158
159 class UnprocessableEntityError(APIStatusError):
160 status_code: Literal[422] = 422 # pyright: ignore[reportIncompatibleVariableOverride]
161
162
163 class RateLimitError(APIStatusError):
164 status_code: Literal[429] = 429 # pyright: ignore[reportIncompatibleVariableOverride]
165
166
167 class ServiceUnavailableError(APIStatusError):
168 status_code: Literal[503] = 503 # pyright: ignore[reportIncompatibleVariableOverride]
169
170
171 class OverloadedError(APIStatusError):
172 status_code: Literal[529] = 529 # pyright: ignore[reportIncompatibleVariableOverride]
173
174
175 class DeadlineExceededError(APIStatusError):
176 status_code: Literal[504] = 504 # pyright: ignore[reportIncompatibleVariableOverride]
177
178
179 class InternalServerError(APIStatusError):
180 pass