Routes Manager for FastAPI
Standardize and handle exceptions in FastAPI more elegantly.
Installation
$ pip install fastapi-exceptionshandler
Example
from fastapi import FastAPI
from fastapi_exceptionshandler import APIExceptionMiddleware
app = FastAPI()
# Register the middleware
app.add_middleware(APIExceptionMiddleware, capture_unhandled=True) # Capture all exceptions
# You can also capture Validation errors, that are not captured by default
from fastapi_exceptionshandler import APIExceptionHandler
from pydantic import ValidationError
app.add_exception_handler(ValidationError, APIExceptionHandler.unhandled)
from fastapi.exceptions import RequestValidationError
app.add_exception_handler(RequestValidationError, APIExceptionHandler.unhandled)
@app.get("/")
def read_root():
return 1/0
Run it
$ uvicorn main:app --reload
Check it
Browse to http://127.0.0.1:8000 you should see this json:
{"errorCode": "InternalError", "message": "Internal Server Error"}
Creating custom exceptions
In order to create a custom exception you need to extend APIException and ErrorCodeBase classes.
Note: if you want to capture only APIException then don't send the capture_unhandled param, or set it to False
from fastapi import FastAPI
from fastapi_exceptionshandler import APIExceptionMiddleware, APIException, ErrorCodeBase
from starlette import status
app = FastAPI()
# Register the middleware
app.add_middleware(APIExceptionMiddleware)
class CustomException(APIException):
status_code = status.HTTP_400_BAD_REQUEST
class ErrorCode(ErrorCodeBase):
CustomExceptionCode = "Custom Exception Message", status.HTTP_401_UNAUTHORIZED
CustomExceptionCodeWithDefaultStatusCode = "Custom Exception Message"
@app.get("/")
def read_root():
raise CustomException(CustomException.ErrorCode.CustomExceptionCode)
Then you should get a 401 response with this body
{"errorCode": "CustomExceptionCode", "message": "Custom Exception Message"}
Or you can handle exceptions manually...
@app.get("/")
def read_root():
try:
raise CustomException(CustomException.ErrorCode.CustomExceptionCode)
except APIException as exc:
return await APIExceptionHandler.handled(exc)
except Exception as exc: # Handle all exceptions
return await APIExceptionHandler.unhandled(exc)
Note: The ErrorCode class doesn't need to be inside CustomException and can be shared with another exceptions as well.
Metadata
Release files for fastapi-exceptionshandler 0.1.2
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| fastapi_exceptionshandler-0.1.2.tar.gz | 4.6 kB | Without provenance | Details for fastapi_exceptionshandler-0.1.2.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| fastapi_exceptionshandler-0.1.2-py3-none-any.whl | Python 3 | none | any | Details for fastapi_exceptionshandler-0.1.2-py3-none-any.whl |
Total release size: 10.6 kB
Release files / fastapi_exceptionshandler-0.1.2.tar.gz
| Download URL | fastapi_exceptionshandler-0.1.2.tar.gz |
|---|---|
| Size | 4.6 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
feff01ca835d6d0f8b60f8a229b083d63ceffee0aa0aa0705ff07b2da6b1ee48
|
|
BLAKE2b-256 checksum How to use checksums |
4dc8a15fb3bcea590594f158d5c9c0c52c4dddc42ff8b2ace0df0d8589b314ba
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.0.1 CPython/3.9.21
|
Release files / fastapi_exceptionshandler-0.1.2-py3-none-any.whl
| Download URL | fastapi_exceptionshandler-0.1.2-py3-none-any.whl |
|---|---|
| Size | 5.9 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
a593c8665826d6e93e03e1130e31d2708952664a044d961b83ec8372998b025e
|
|
BLAKE2b-256 checksum How to use checksums |
60989b625af88f8be076bf70b0eb1551f4700ca6cdf7210020317a6bea5bbbe7
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.0.1 CPython/3.9.21
|
Security for fastapi-exceptionshandler 0.1.2
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.