Home
About
Blog
Products
Forum
Support
Contact
Sunbelt Computer Software
PL/B Language Development and Support
Home
About
Blog
Products
Forum
Support
Contact
fastapi/fastapi/exceptions.py at a497a025e7114ca442478ed28da7e0a1cdc6177a · fastapi/fastapi · GitHub
Skip to content
Navigation Menu
Sign in
Appearance settings
Platform
AI CODE CREATION
GitHub Copilot
Write better code with AI
GitHub Copilot app
Direct agents from issue to merge
MCP Registry
Integrate external tools
DEVELOPER WORKFLOWS
Actions
Automate any workflow
Codespaces
Instant dev environments
Issues
Plan and track work
Code Review
Manage code changes
Code Quality
Enforce quality at merge
APPLICATION SECURITY
GitHub Advanced Security
Find and fix vulnerabilities
Code security
Secure your code as you build
Secret protection
Stop leaks before they start
EXPLORE
Why GitHub
Documentation
Blog
Changelog
Marketplace
View all features
Solutions
BY COMPANY SIZE
Enterprises
Small and medium teams
Startups
Nonprofits
BY USE CASE
App Modernization
DevSecOps
DevOps
CI/CD
View all use cases
BY INDUSTRY
Healthcare
Financial services
Manufacturing
Government
View all industries
View all solutions
Resources
EXPLORE BY TOPIC
AI
Software Development
DevOps
Security
View all topics
EXPLORE BY TYPE
Customer stories
Events & webinars
Ebooks & reports
Business insights
GitHub Skills
SUPPORT & SERVICES
Documentation
Customer support
Community forum
Trust center
Partners
View all resources
Open Source
COMMUNITY
GitHub Sponsors
Fund open source developers
PROGRAMS
Security Lab
Maintainer Community
GitHub Stars
Archive Program
REPOSITORIES
Topics
Trending
Collections
Enterprise
ENTERPRISE SOLUTIONS
Enterprise platform
AI-powered developer platform
AVAILABLE ADD-ONS
GitHub Advanced Security
Enterprise-grade security features
Copilot for Business
Enterprise-grade AI features
Premium Support
Enterprise-grade 24/7 support
Pricing
Search
/
Sign in
Sign up
Appearance settings
You signed in with another tab or window.
Reload
to refresh your session.
You signed out in another tab or window.
Reload
to refresh your session.
You switched accounts on another tab or window.
Reload
to refresh your session.
Dismiss alert
{{ message }}
Uh oh!
There was an error while loading.
Please reload this page
.
fastapi
/
fastapi
Public
Uh oh!
There was an error while loading.
Please reload this page
.
Notifications
You must be signed in to change notification settings
Fork
9.9k
Star
102k
Code
Issues
2
Pull requests
88
Discussions
Actions
Projects
Security and quality
1
Insights
Additional navigation options
Code
Issues
Pull requests
Discussions
Actions
Projects
Security and quality
Insights
Files
Expand file tree
a497a025e7114ca442478ed28da7e0a1cdc6177a
Breadcrumbs
fastapi
/
fastapi
/
exceptions.py
Copy path
Blame
More file actions
Blame
More file actions
Latest commit
History
History
History
256 lines (203 loc) · 7.28 KB
a497a02
Breadcrumbs
fastapi
/
fastapi
/
exceptions.py
Copy path
Top
File metadata and controls
Code
Blame
256 lines (203 loc) · 7.28 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
from
collections
.
abc
import
Mapping
,
Sequence
from
typing
import
Annotated
,
Any
,
TypedDict
from
annotated_doc
import
Doc
from
pydantic
import
BaseModel
,
create_model
from
starlette
.
exceptions
import
HTTPException
as
StarletteHTTPException
from
starlette
.
exceptions
import
WebSocketException
as
StarletteWebSocketException
class
EndpointContext
(
TypedDict
,
total
=
False
):
function
:
str
path
:
str
file
:
str
line
:
int
class
HTTPException
(
StarletteHTTPException
):
"""
An HTTP exception you can raise in your own code to show errors to the client.
This is for client errors, invalid authentication, invalid data, etc. Not for server
errors in your code.
Read more about it in the
[FastAPI docs for Handling Errors](https://fastapi.tiangolo.com/tutorial/handling-errors/).
## Example
```python
from fastapi import FastAPI, HTTPException
app = FastAPI()
items = {"foo": "The Foo Wrestlers"}
@app.get("/items/{item_id}")
async def read_item(item_id: str):
if item_id not in items:
raise HTTPException(status_code=404, detail="Item not found")
return {"item": items[item_id]}
```
"""
def
__init__
(
self
,
status_code
:
Annotated
[
int
,
Doc
(
"""
HTTP status code to send to the client.
Read more about it in the
[FastAPI docs for Handling Errors](https://fastapi.tiangolo.com/tutorial/handling-errors/#use-httpexception)
"""
),
],
detail
:
Annotated
[
Any
,
Doc
(
"""
Any data to be sent to the client in the `detail` key of the JSON
response.
Read more about it in the
[FastAPI docs for Handling Errors](https://fastapi.tiangolo.com/tutorial/handling-errors/#use-httpexception)
"""
),
]
=
None
,
headers
:
Annotated
[
Mapping
[
str
,
str
]
|
None
,
Doc
(
"""
Any headers to send to the client in the response.
Read more about it in the
[FastAPI docs for Handling Errors](https://fastapi.tiangolo.com/tutorial/handling-errors/#add-custom-headers)
"""
),
]
=
None
,
)
->
None
:
super
().
__init__
(
status_code
=
status_code
,
detail
=
detail
,
headers
=
headers
)
class
WebSocketException
(
StarletteWebSocketException
):
"""
A WebSocket exception you can raise in your own code to show errors to the client.
This is for client errors, invalid authentication, invalid data, etc. Not for server
errors in your code.
Read more about it in the
[FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).
## Example
```python
from typing import Annotated
from fastapi import (
Cookie,
FastAPI,
WebSocket,
WebSocketException,
status,
)
app = FastAPI()
@app.websocket("/items/{item_id}/ws")
async def websocket_endpoint(
*,
websocket: WebSocket,
session: Annotated[str | None, Cookie()] = None,
item_id: str,
):
if session is None:
raise WebSocketException(code=status.WS_1008_POLICY_VIOLATION)
await websocket.accept()
while True:
data = await websocket.receive_text()
await websocket.send_text(f"Session cookie is: {session}")
await websocket.send_text(f"Message text was: {data}, for item ID: {item_id}")
```
"""
def
__init__
(
self
,
code
:
Annotated
[
int
,
Doc
(
"""
A closing code from the
[valid codes defined in the specification](https://datatracker.ietf.org/doc/html/rfc6455#section-7.4.1).
"""
),
],
reason
:
Annotated
[
str
|
None
,
Doc
(
"""
The reason to close the WebSocket connection.
It is UTF-8-encoded data. The interpretation of the reason is up to the
application, it is not specified by the WebSocket specification.
It could contain text that could be human-readable or interpretable
by the client code, etc.
"""
),
]
=
None
,
)
->
None
:
super
().
__init__
(
code
=
code
,
reason
=
reason
)
RequestErrorModel
:
type
[
BaseModel
]
=
create_model
(
"Request"
)
WebSocketErrorModel
:
type
[
BaseModel
]
=
create_model
(
"WebSocket"
)
class
FastAPIError
(
RuntimeError
):
"""
A generic, FastAPI-specific error.
"""
class
DependencyScopeError
(
FastAPIError
):
"""
A dependency declared that it depends on another dependency with an invalid
(narrower) scope.
"""
class
ValidationException
(
Exception
):
def
__init__
(
self
,
errors
:
Sequence
[
Any
],
*
,
endpoint_ctx
:
EndpointContext
|
None
=
None
,
)
->
None
:
self
.
_errors
=
errors
self
.
endpoint_ctx
=
endpoint_ctx
ctx
=
endpoint_ctx
or
{}
self
.
endpoint_function
=
ctx
.
get
(
"function"
)
self
.
endpoint_path
=
ctx
.
get
(
"path"
)
self
.
endpoint_file
=
ctx
.
get
(
"file"
)
self
.
endpoint_line
=
ctx
.
get
(
"line"
)
def
errors
(
self
)
->
Sequence
[
Any
]:
return
self
.
_errors
def
_format_endpoint_context
(
self
)
->
str
:
if
not
(
self
.
endpoint_file
and
self
.
endpoint_line
and
self
.
endpoint_function
):
if
self
.
endpoint_path
:
return
f"
\n
Endpoint:
{
self
.
endpoint_path
}
"
return
""
context
=
f'
\n
File "
{
self
.
endpoint_file
}
", line
{
self
.
endpoint_line
}
, in
{
self
.
endpoint_function
}
'
if
self
.
endpoint_path
:
context
+=
f"
\n
{
self
.
endpoint_path
}
"
return
context
def
__str__
(
self
)
->
str
:
message
=
f"
{
len
(
self
.
_errors
)
}
validation error
{
's'
if
len
(
self
.
_errors
)
!=
1
else
''
}
:
\n
"
for
err
in
self
.
_errors
:
message
+=
f"
{
err
}
\n
"
message
+=
self
.
_format_endpoint_context
()
return
message
.
rstrip
()
class
RequestValidationError
(
ValidationException
):
def
__init__
(
self
,
errors
:
Sequence
[
Any
],
*
,
body
:
Any
=
None
,
endpoint_ctx
:
EndpointContext
|
None
=
None
,
)
->
None
:
super
().
__init__
(
errors
,
endpoint_ctx
=
endpoint_ctx
)
self
.
body
=
body
class
WebSocketRequestValidationError
(
ValidationException
):
def
__init__
(
self
,
errors
:
Sequence
[
Any
],
*
,
endpoint_ctx
:
EndpointContext
|
None
=
None
,
)
->
None
:
super
().
__init__
(
errors
,
endpoint_ctx
=
endpoint_ctx
)
class
ResponseValidationError
(
ValidationException
):
def
__init__
(
self
,
errors
:
Sequence
[
Any
],
*
,
body
:
Any
=
None
,
endpoint_ctx
:
EndpointContext
|
None
=
None
,
)
->
None
:
super
().
__init__
(
errors
,
endpoint_ctx
=
endpoint_ctx
)
self
.
body
=
body
class
PydanticV1NotSupportedError
(
FastAPIError
):
"""
A pydantic.v1 model is used, which is no longer supported.
"""
class
FastAPIDeprecationWarning
(
UserWarning
):
"""
A custom deprecation warning as DeprecationWarning is ignored
Ref: https://sethmlarson.dev/deprecations-via-warnings-dont-work-for-python-libraries
"""
You can’t perform that action at this time.