fastapi-error-map 0.1.0__tar.gz → 0.9.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- fastapi_error_map-0.9.0/.github/workflows/ci.yaml +32 -0
- fastapi_error_map-0.9.0/.github/workflows/test-compatibility.yaml +38 -0
- fastapi_error_map-0.9.0/LICENSE +201 -0
- fastapi_error_map-0.9.0/PKG-INFO +320 -0
- fastapi_error_map-0.9.0/README.md +281 -0
- fastapi_error_map-0.9.0/docs/example-openapi.png +0 -0
- fastapi_error_map-0.9.0/examples/errors.py +29 -0
- fastapi_error_map-0.9.0/examples/main.py +53 -0
- fastapi_error_map-0.9.0/fastapi_error_map/__init__.py +10 -0
- fastapi_error_map-0.9.0/fastapi_error_map/error_handling.py +69 -0
- fastapi_error_map-0.9.0/fastapi_error_map/openapi.py +26 -0
- fastapi_error_map-0.9.0/fastapi_error_map/routing.py +2554 -0
- fastapi_error_map-0.9.0/fastapi_error_map/rules.py +83 -0
- fastapi_error_map-0.9.0/fastapi_error_map/translators.py +75 -0
- fastapi_error_map-0.9.0/noxfile.py +13 -0
- {fastapi_error_map-0.1.0 → fastapi_error_map-0.9.0}/pyproject.toml +48 -11
- fastapi_error_map-0.9.0/tests/integration/test_example.py +37 -0
- fastapi_error_map-0.9.0/tests/integration/test_routing.py +54 -0
- fastapi_error_map-0.9.0/tests/unit/__init__.py +0 -0
- fastapi_error_map-0.9.0/tests/unit/error_stubs.py +10 -0
- fastapi_error_map-0.9.0/tests/unit/test_error_handling.py +128 -0
- fastapi_error_map-0.9.0/tests/unit/test_openapi.py +48 -0
- fastapi_error_map-0.9.0/tests/unit/test_rules.py +87 -0
- fastapi_error_map-0.9.0/tests/unit/test_translators.py +43 -0
- fastapi_error_map-0.9.0/tests/unit/translator_stubs.py +28 -0
- fastapi_error_map-0.9.0/uv.lock +1492 -0
- fastapi_error_map-0.1.0/LICENSE +0 -21
- fastapi_error_map-0.1.0/PKG-INFO +0 -17
- fastapi_error_map-0.1.0/fastapi_error_map/__init__.py +0 -2
- fastapi_error_map-0.1.0/tests/test_temp.py +0 -2
- fastapi_error_map-0.1.0/uv.lock +0 -1290
- {fastapi_error_map-0.1.0 → fastapi_error_map-0.9.0}/.gitignore +0 -0
- {fastapi_error_map-0.1.0 → fastapi_error_map-0.9.0}/.pre-commit-config.yaml +0 -0
- {fastapi_error_map-0.1.0 → fastapi_error_map-0.9.0}/Makefile +0 -0
- {fastapi_error_map-0.1.0 → fastapi_error_map-0.9.0}/examples/__init__.py +0 -0
- {fastapi_error_map-0.1.0 → fastapi_error_map-0.9.0}/fastapi_error_map/py.typed +0 -0
- {fastapi_error_map-0.1.0 → fastapi_error_map-0.9.0}/tests/__init__.py +0 -0
- /fastapi_error_map-0.1.0/README.md → /fastapi_error_map-0.9.0/tests/integration/__init__.py +0 -0
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
name: CI
|
|
2
|
+
|
|
3
|
+
on: [ push, pull_request ]
|
|
4
|
+
|
|
5
|
+
jobs:
|
|
6
|
+
test:
|
|
7
|
+
runs-on: ubuntu-latest
|
|
8
|
+
|
|
9
|
+
steps:
|
|
10
|
+
- uses: actions/checkout@v4
|
|
11
|
+
|
|
12
|
+
- name: Set up Python
|
|
13
|
+
uses: actions/setup-python@v5
|
|
14
|
+
with:
|
|
15
|
+
python-version: "3.9"
|
|
16
|
+
|
|
17
|
+
- name: Install uv
|
|
18
|
+
uses: astral-sh/setup-uv@v6
|
|
19
|
+
|
|
20
|
+
- name: Install dependencies
|
|
21
|
+
run: uv pip install -e '.[dev,test]' --system
|
|
22
|
+
|
|
23
|
+
- name: Lint code
|
|
24
|
+
run: make code.lint
|
|
25
|
+
|
|
26
|
+
- name: Run tests for Codecov
|
|
27
|
+
run: pytest --cov=fastapi_error_map --cov-branch --cov-report=xml
|
|
28
|
+
|
|
29
|
+
- name: Upload coverage reports to Codecov
|
|
30
|
+
uses: codecov/codecov-action@v5
|
|
31
|
+
with:
|
|
32
|
+
token: ${{ secrets.CODECOV_TOKEN }}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
name: TestCompatibility
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
push:
|
|
5
|
+
pull_request:
|
|
6
|
+
workflow_dispatch:
|
|
7
|
+
schedule:
|
|
8
|
+
- cron: "0 0 * * *"
|
|
9
|
+
|
|
10
|
+
jobs:
|
|
11
|
+
compatibility:
|
|
12
|
+
runs-on: ${{ matrix.os }}
|
|
13
|
+
strategy:
|
|
14
|
+
matrix:
|
|
15
|
+
os:
|
|
16
|
+
- ubuntu-latest
|
|
17
|
+
python-version:
|
|
18
|
+
- "3.9"
|
|
19
|
+
- "3.10"
|
|
20
|
+
- "3.11"
|
|
21
|
+
- "3.12"
|
|
22
|
+
- "3.13"
|
|
23
|
+
|
|
24
|
+
steps:
|
|
25
|
+
- uses: actions/checkout@v4
|
|
26
|
+
- name: Set up ${{ matrix.python-version }} on ${{ matrix.os }}
|
|
27
|
+
uses: actions/setup-python@v5
|
|
28
|
+
with:
|
|
29
|
+
python-version: ${{ matrix.python-version }}
|
|
30
|
+
|
|
31
|
+
- name: Install uv
|
|
32
|
+
uses: astral-sh/setup-uv@v6
|
|
33
|
+
|
|
34
|
+
- name: Install nox
|
|
35
|
+
run: uv pip install nox --system
|
|
36
|
+
|
|
37
|
+
- name: Run tests
|
|
38
|
+
run: nox -s compatibility
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2025 Ivan Borovets
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
@@ -0,0 +1,320 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: fastapi-error-map
|
|
3
|
+
Version: 0.9.0
|
|
4
|
+
Summary: Elegant per-endpoint error handling in FastAPI with OpenAPI schema generation
|
|
5
|
+
Author-email: Ivan Borovets <ivan.r.borovets@gmail.com>
|
|
6
|
+
License: Apache-2.0
|
|
7
|
+
License-File: LICENSE
|
|
8
|
+
Classifier: Framework :: FastAPI
|
|
9
|
+
Classifier: Intended Audience :: Developers
|
|
10
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
11
|
+
Classifier: Operating System :: OS Independent
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
18
|
+
Classifier: Topic :: Software Development :: Libraries
|
|
19
|
+
Classifier: Typing :: Typed
|
|
20
|
+
Requires-Python: >=3.9
|
|
21
|
+
Requires-Dist: fastapi>=0.100.0
|
|
22
|
+
Requires-Dist: orjson>=3.11.1
|
|
23
|
+
Provides-Extra: dev
|
|
24
|
+
Requires-Dist: mypy==1.8.0; extra == 'dev'
|
|
25
|
+
Requires-Dist: pre-commit==4.2.0; extra == 'dev'
|
|
26
|
+
Requires-Dist: ruff==0.11.2; extra == 'dev'
|
|
27
|
+
Provides-Extra: examples
|
|
28
|
+
Requires-Dist: uvicorn==0.35.0; extra == 'examples'
|
|
29
|
+
Provides-Extra: publish
|
|
30
|
+
Requires-Dist: hatch==1.14.1; extra == 'publish'
|
|
31
|
+
Provides-Extra: test
|
|
32
|
+
Requires-Dist: coverage==7.10.1; extra == 'test'
|
|
33
|
+
Requires-Dist: httpx==0.28.1; extra == 'test'
|
|
34
|
+
Requires-Dist: nox==2025.5.1; extra == 'test'
|
|
35
|
+
Requires-Dist: pytest-asyncio==1.1.0; extra == 'test'
|
|
36
|
+
Requires-Dist: pytest-cov==6.2.1; extra == 'test'
|
|
37
|
+
Requires-Dist: pytest==8.4.1; extra == 'test'
|
|
38
|
+
Description-Content-Type: text/markdown
|
|
39
|
+
|
|
40
|
+
## FastAPI Error Map
|
|
41
|
+
|
|
42
|
+
[](https://badge.fury.io/py/fastapi-error-map)
|
|
43
|
+

|
|
44
|
+

|
|
45
|
+

|
|
46
|
+
|
|
47
|
+
Elegant per-endpoint error handling in FastAPI with OpenAPI schema generation.
|
|
48
|
+
|
|
49
|
+
### 📦 Installation
|
|
50
|
+
|
|
51
|
+
```bash
|
|
52
|
+
pip install fastapi-error-map
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
### 🚀 Quickstart
|
|
56
|
+
|
|
57
|
+
```python
|
|
58
|
+
# A seamless replacement for APIRouter with error mapping support
|
|
59
|
+
router = ErrorAwareRouter()
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
@router.get(
|
|
63
|
+
"/stock",
|
|
64
|
+
error_map={
|
|
65
|
+
# Minimal rule: return 401 and respond with {"error": "..."}
|
|
66
|
+
# using default translator
|
|
67
|
+
AuthorizationError: 401,
|
|
68
|
+
# Full rule: return 409 and respond with custom JSON
|
|
69
|
+
# using custom translator, and trigger side effect
|
|
70
|
+
OutOfStockError: rule(
|
|
71
|
+
status=409,
|
|
72
|
+
translator=OutOfStockTranslator(),
|
|
73
|
+
on_error=notify,
|
|
74
|
+
),
|
|
75
|
+
},
|
|
76
|
+
)
|
|
77
|
+
def check_stock(user_id: int = 0) -> None:
|
|
78
|
+
if user_id == 0:
|
|
79
|
+
raise AuthorizationError
|
|
80
|
+
raise OutOfStockError("No items available.")
|
|
81
|
+
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
- Fully compatible with `APIRouter`
|
|
85
|
+
- Error handling centralized at the endpoint level
|
|
86
|
+
- OpenAPI schema automatically generated
|
|
87
|
+
|
|
88
|
+
<div align="center">
|
|
89
|
+
<img src="docs/example-openapi.png" alt="Example OpenAPI" width="600"/>
|
|
90
|
+
<p><em>Figure 1: Example OpenAPI</em></p>
|
|
91
|
+
</div>
|
|
92
|
+
|
|
93
|
+
### 🔍 Why Not Global Handlers?
|
|
94
|
+
|
|
95
|
+
To convert application errors into HTTP responses, FastAPI allows attaching exception handlers to the app instance.
|
|
96
|
+
These handlers are global, which makes it harder to customize the response based on context and can become a source of
|
|
97
|
+
hidden bugs.
|
|
98
|
+
|
|
99
|
+
```python
|
|
100
|
+
app.add_exception_handler(UserNotFoundError, error_handler)
|
|
101
|
+
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
For example, `error_handler` might turn `UserNotFoundError` into `404 Not Found`.
|
|
105
|
+
But in an authentication context, it might mean `401 Unauthorized`, and in a communication scenario —
|
|
106
|
+
`422 Unprocessable Entity`.
|
|
107
|
+
The fact that a user is missing carries different meaning in different situations.
|
|
108
|
+
|
|
109
|
+
If accuracy and clarity in your API matter more than the short-term convenience of global (and implicit) exception
|
|
110
|
+
interception, prefer handling exceptions directly in the route — where full context is available: request type, business
|
|
111
|
+
scenario, and client expectations.
|
|
112
|
+
|
|
113
|
+
You could use `try/except` blocks or a decorator with error mapping.
|
|
114
|
+
The first doesn't keep your views clean and duplicates logic between routes.
|
|
115
|
+
The second solves that, but like the first, remains invisible to FastAPI: the framework can't extract possible responses
|
|
116
|
+
from your decorator to include in the OpenAPI schema.
|
|
117
|
+
You could define `responses` manually, but that risks a mismatch between the schema and actual behavior — because
|
|
118
|
+
there's no single source of truth.
|
|
119
|
+
|
|
120
|
+
`fastapi-error-map` solves this by letting you define error handling rules right in the route declaration.
|
|
121
|
+
See the [example in the 🚀 Quickstart](#-quickstart).
|
|
122
|
+
|
|
123
|
+
### ⚙ How `error_map` Works
|
|
124
|
+
|
|
125
|
+
Error handling rules are defined directly in the route declaration of an `ErrorAwareRouter`, using the `error_map`
|
|
126
|
+
parameter.
|
|
127
|
+
|
|
128
|
+
There are two ways to do it:
|
|
129
|
+
|
|
130
|
+
#### 🔸 Short Form
|
|
131
|
+
|
|
132
|
+
```python
|
|
133
|
+
error_map = {
|
|
134
|
+
SomeError: 400,
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
Which is equivalent to:
|
|
140
|
+
|
|
141
|
+
```python
|
|
142
|
+
error_map = {
|
|
143
|
+
SomeError: rule(status=400),
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
In both cases, the default translator is used, which returns JSON like:
|
|
149
|
+
|
|
150
|
+
```json
|
|
151
|
+
{
|
|
152
|
+
"error": "SomeError"
|
|
153
|
+
}
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
#### 🔹 Full Form
|
|
157
|
+
|
|
158
|
+
Allows you to specify the status code, and optionally a `translator` and `on_error`:
|
|
159
|
+
|
|
160
|
+
```python
|
|
161
|
+
error_map = {
|
|
162
|
+
MyError: rule(
|
|
163
|
+
status=409,
|
|
164
|
+
translator=MyTranslator(),
|
|
165
|
+
on_error=report_to_sentry,
|
|
166
|
+
),
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
Parameters of `rule(...)`, * — required:
|
|
172
|
+
|
|
173
|
+
- `status`* — HTTP status code to return (e.g. `404`, `409`, `422`)
|
|
174
|
+
- `translator` — object that converts an exception into JSON response. If not provided, the default one is used (returns
|
|
175
|
+
`{ "error": "..." }`)
|
|
176
|
+
- `on_error` — function to call when an exception occurs (e.g. logging or alerting)
|
|
177
|
+
|
|
178
|
+
### 🧰 Custom Translators
|
|
179
|
+
|
|
180
|
+
If you want to change the error response format, define your own `translator` — object that implements `ErrorTranslator`
|
|
181
|
+
protocol.
|
|
182
|
+
It has:
|
|
183
|
+
|
|
184
|
+
- `.from_error(err)` — turns exception into serializable object
|
|
185
|
+
- `.error_response_model_cls` — returns a class describing object structure (used for OpenAPI)
|
|
186
|
+
|
|
187
|
+
Example:
|
|
188
|
+
|
|
189
|
+
```python
|
|
190
|
+
from dataclasses import dataclass
|
|
191
|
+
from fastapi_error_map.translators import ErrorTranslator
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
@dataclass
|
|
195
|
+
class MyErrorResponse:
|
|
196
|
+
type: str
|
|
197
|
+
message: str
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
class MyTranslator(ErrorTranslator[MyErrorResponse]):
|
|
201
|
+
@property
|
|
202
|
+
def error_response_model_cls(self) -> type[MyErrorResponse]:
|
|
203
|
+
return MyErrorResponse
|
|
204
|
+
|
|
205
|
+
def from_error(self, err: Exception) -> MyErrorResponse:
|
|
206
|
+
return MyErrorResponse(
|
|
207
|
+
type=type(err).__name__,
|
|
208
|
+
message=str(err),
|
|
209
|
+
)
|
|
210
|
+
|
|
211
|
+
```
|
|
212
|
+
|
|
213
|
+
### 🔄 Side Effects (`on_error`)
|
|
214
|
+
|
|
215
|
+
The `on_error` parameter in `rule(...)` allows specifying function to run when exception occurs, before response is
|
|
216
|
+
generated.
|
|
217
|
+
It doesn't affect the HTTP response, but it's useful for:
|
|
218
|
+
|
|
219
|
+
- logging
|
|
220
|
+
- sending alerts
|
|
221
|
+
- metrics
|
|
222
|
+
- debugging
|
|
223
|
+
|
|
224
|
+
Example:
|
|
225
|
+
|
|
226
|
+
```python
|
|
227
|
+
def notify_admin(err: Exception) -> None:
|
|
228
|
+
print(f"[!] Error: {type(err).__name__} — {err}")
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
error_map = {
|
|
232
|
+
DangerousOperationError: rule(
|
|
233
|
+
status=500,
|
|
234
|
+
translator=MyTranslator(),
|
|
235
|
+
on_error=notify_admin,
|
|
236
|
+
),
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
```
|
|
240
|
+
|
|
241
|
+
### 🧠 Parameter Precedence
|
|
242
|
+
|
|
243
|
+
Error handling and schema generation in `fastapi-error-map` are fully driven by route-level arguments to `.get()`,
|
|
244
|
+
`.post()`, etc.
|
|
245
|
+
|
|
246
|
+
#### 📎 Core Parameters
|
|
247
|
+
|
|
248
|
+
In addition to `error_map`, you can also pass:
|
|
249
|
+
|
|
250
|
+
```
|
|
251
|
+
@router.get(
|
|
252
|
+
"/path",
|
|
253
|
+
error_map=...,
|
|
254
|
+
default_on_error=...,
|
|
255
|
+
warn_on_unmapped=...,
|
|
256
|
+
default_client_error_translator=...,
|
|
257
|
+
default_server_error_translator=...,
|
|
258
|
+
)
|
|
259
|
+
```
|
|
260
|
+
|
|
261
|
+
These parameters apply to the current route only.
|
|
262
|
+
They are not set on the router level (for now).
|
|
263
|
+
|
|
264
|
+
#### ➕ How Parameters Are Resolved
|
|
265
|
+
|
|
266
|
+
When an error occurs, `fastapi-error-map` processes it as follows:
|
|
267
|
+
|
|
268
|
+
1. `status` is taken from `rule(...)`, or from short form: `SomeError: 400`
|
|
269
|
+
2. `translator`:
|
|
270
|
+
|
|
271
|
+
- If provided in `rule(...)`, it is used
|
|
272
|
+
- Otherwise:
|
|
273
|
+
- If the status is `< 500`, `default_client_error_translator` is used (if given)
|
|
274
|
+
- If the status is `>= 500`, `default_server_error_translator` is used (if given)
|
|
275
|
+
- If none are set, the built-in one is used:
|
|
276
|
+
```raw
|
|
277
|
+
{ "error": "..." } or { "error": "Internal server error" }
|
|
278
|
+
```
|
|
279
|
+
|
|
280
|
+
3. `on_error`:
|
|
281
|
+
- If provided in `rule(...)`, it is used
|
|
282
|
+
- Otherwise, `default_on_error` is used if provided
|
|
283
|
+
- If neither is set, nothing is called
|
|
284
|
+
|
|
285
|
+
#### 🧾 OpenAPI: `responses` Takes Priority
|
|
286
|
+
|
|
287
|
+
If you explicitly pass the `responses=...` parameter to `.get(...)` / `.post(...)`, it overrides the schema generation
|
|
288
|
+
from `error_map` — but only for the specified status codes.
|
|
289
|
+
|
|
290
|
+
```python
|
|
291
|
+
@router.get(
|
|
292
|
+
"/foo",
|
|
293
|
+
error_map={SomeError: 400},
|
|
294
|
+
responses={400: {"model": {}}}, # ← this wins
|
|
295
|
+
)
|
|
296
|
+
|
|
297
|
+
```
|
|
298
|
+
|
|
299
|
+
#### 🚨 Handling Unmapped Exceptions (`warn_on_unmapped`)
|
|
300
|
+
|
|
301
|
+
By default (`warn_on_unmapped=True`), `fastapi-error-map` expects every exception raised in a handler to be explicitly
|
|
302
|
+
listed in `error_map`.
|
|
303
|
+
If a rule is missing, a `RuntimeError` is raised, and the original exception is attached as `__cause__`.
|
|
304
|
+
This helps you catch missing error cases at runtime.
|
|
305
|
+
|
|
306
|
+
If you set `warn_on_unmapped=False`, the library won’t complain about missing rules and will re-raise the exception
|
|
307
|
+
as-is.
|
|
308
|
+
In that case:
|
|
309
|
+
|
|
310
|
+
- the exception type is preserved
|
|
311
|
+
- the original stack trace is retained
|
|
312
|
+
- the global `@app.exception_handler(...)` in FastAPI will receive raw exception
|
|
313
|
+
|
|
314
|
+
#### 📘 Handling by FastAPI
|
|
315
|
+
|
|
316
|
+
FastAPI will always catch unhandled exceptions and pass them to the global `@app.exception_handler(...)` if defined.
|
|
317
|
+
This behavior is not affected by `warn_on_unmapped`.
|
|
318
|
+
|
|
319
|
+
If the error is declared in `error_map`, `fastapi-error-map` handles the response itself — the global handler will not
|
|
320
|
+
be triggered.
|