Standardize and handle exceptions in FastAPI more elegantly
Project description
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.
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
File details
Details for the file fastapi_exceptionshandler-0.1.1.tar.gz
.
File metadata
- Download URL: fastapi_exceptionshandler-0.1.1.tar.gz
- Upload date:
- Size: 4.6 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/5.1.1 CPython/3.9.19
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | f93dd88da5e0e96fdddeaa86aaf9249fe73599e8e1e4d6c035030346bf545108 |
|
MD5 | 3be29e7784b9a8c0ac71b142a4f54044 |
|
BLAKE2b-256 | 054b912e914897361c860e9a1fcbd45ab380b44cfdaf0a36b0f4558ab5c2686e |
File details
Details for the file fastapi_exceptionshandler-0.1.1-py3-none-any.whl
.
File metadata
- Download URL: fastapi_exceptionshandler-0.1.1-py3-none-any.whl
- Upload date:
- Size: 5.8 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/5.1.1 CPython/3.9.19
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 004a5e9534142fa6b068f0ecd2fae84fedec061eeff1deb103bc23e5b6eec8a6 |
|
MD5 | 92b5d789bf8e1aa28754897dee9a8ae7 |
|
BLAKE2b-256 | 665ace02be1bb75af5b21d07ccf5b1dcd16ad13b9bf1c6d5ca44788376be4990 |