0
# Exception Handling
1
2
Comprehensive exception hierarchy for GitHub API error responses, providing specific exception types for different HTTP status codes and error conditions. This enables precise error handling and appropriate responses to various GitHub API failure scenarios.
3
4
## Capabilities
5
6
### Base Exceptions
7
8
Core exception classes that form the foundation of the gidgethub exception hierarchy.
9
10
```python { .api }
11
class GitHubException(Exception):
12
"""Base exception for this library."""
13
14
class ValidationFailure(GitHubException):
15
"""An exception representing failed validation of a webhook event."""
16
```
17
18
### HTTP Exceptions
19
20
Exception classes for HTTP response status codes with detailed error information.
21
22
```python { .api }
23
class HTTPException(GitHubException):
24
"""A general exception to represent HTTP responses."""
25
26
def __init__(self, status_code: http.HTTPStatus, *args: Any) -> None: ...
27
28
# Attributes
29
status_code: http.HTTPStatus
30
31
class RedirectionException(HTTPException):
32
"""Exception for 3XX HTTP responses."""
33
34
class GitHubBroken(HTTPException):
35
"""Exception for 5XX HTTP responses."""
36
```
37
38
### Client Error Exceptions
39
40
Exception classes for 4XX HTTP status codes representing client-side errors.
41
42
```python { .api }
43
class BadRequest(HTTPException):
44
"""The request is invalid. Used for 4XX HTTP errors."""
45
46
class BadRequestUnknownError(BadRequest):
47
"""A bad request whose response body is not JSON."""
48
49
def __init__(self, response: str) -> None: ...
50
51
# Attributes
52
response: str
53
54
class RateLimitExceeded(BadRequest):
55
"""Request rejected due to the rate limit being exceeded."""
56
57
def __init__(self, rate_limit: Any, *args: Any) -> None: ...
58
59
# Attributes
60
rate_limit: Any # Actually gidgethub.sansio.RateLimit
61
62
class InvalidField(BadRequest):
63
"""A field in the request is invalid. Represented by a 422 HTTP Response."""
64
65
def __init__(self, errors: Any, *args: Any) -> None: ...
66
67
# Attributes
68
errors: Any
69
70
class ValidationError(BadRequest):
71
"""A request was unable to be completed. Represented by a 422 HTTP response."""
72
73
def __init__(self, errors: Any, *args: Any) -> None: ...
74
75
# Attributes
76
errors: Any
77
```
78
79
### GraphQL Exceptions
80
81
Exception classes specific to GitHub's GraphQL v4 API.
82
83
```python { .api }
84
class GraphQLException(GitHubException):
85
"""Base exception for the GraphQL v4 API."""
86
87
def __init__(self, message: str, response: Any) -> None: ...
88
89
# Attributes
90
response: Any
91
92
class BadGraphQLRequest(GraphQLException):
93
"""A 4XX HTTP response."""
94
95
def __init__(self, status_code: http.HTTPStatus, response: Any) -> None: ...
96
97
# Attributes
98
status_code: http.HTTPStatus
99
100
class GraphQLAuthorizationFailure(BadGraphQLRequest):
101
"""401 HTTP response to a bad oauth token."""
102
103
def __init__(self, response: Any) -> None: ...
104
105
class QueryError(GraphQLException):
106
"""An error occurred while attempting to handle a GraphQL v4 query."""
107
108
def __init__(self, response: Any) -> None: ...
109
110
class GraphQLResponseTypeError(GraphQLException):
111
"""The GraphQL response has an unexpected content type."""
112
113
def __init__(self, content_type: Optional[str], response: Any) -> None: ...
114
```
115
116
## Usage Examples
117
118
### Handling Rate Limits
119
120
```python
121
import asyncio
122
from gidgethub.aiohttp import GitHubAPI
123
from gidgethub import RateLimitExceeded
124
125
async def api_call_with_retry(gh: GitHubAPI, url: str):
126
try:
127
return await gh.getitem(url)
128
except RateLimitExceeded as exc:
129
# Wait until rate limit resets
130
if exc.rate_limit:
131
sleep_time = (exc.rate_limit.reset_datetime -
132
datetime.datetime.now(datetime.timezone.utc)).total_seconds()
133
if sleep_time > 0:
134
await asyncio.sleep(sleep_time)
135
return await gh.getitem(url)
136
raise
137
```
138
139
### Handling Validation Errors
140
141
```python
142
from gidgethub import InvalidField, ValidationError
143
144
async def create_issue(gh: GitHubAPI, repo: str, title: str, body: str):
145
try:
146
return await gh.post(f"/repos/{repo}/issues",
147
data={"title": title, "body": body})
148
except InvalidField as exc:
149
print(f"Invalid fields: {exc.errors}")
150
raise
151
except ValidationError as exc:
152
print(f"Validation failed: {exc.errors}")
153
raise
154
```
155
156
### Handling GraphQL Errors
157
158
```python
159
from gidgethub import QueryError, GraphQLAuthorizationFailure
160
161
async def graphql_query(gh: GitHubAPI, query: str, **variables):
162
try:
163
return await gh.graphql(query, **variables)
164
except GraphQLAuthorizationFailure:
165
print("Invalid or expired OAuth token")
166
raise
167
except QueryError as exc:
168
print(f"GraphQL query error: {exc}")
169
print(f"Response: {exc.response}")
170
raise
171
```
172
173
## Types
174
175
```python { .api }
176
import http
177
from typing import Any, Optional
178
179
# All exception classes inherit from these base types
180
GitHubException = Exception
181
HTTPException = GitHubException
182
BadRequest = HTTPException
183
GraphQLException = GitHubException
184
```