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
You can automatically handle all exceptions using fastapi-routesmanager.
Simply register the APIExceptionManager
to the RouteManagersRegistry
. Don't forget to use the ManagedAPIRouter
Note: by default Validation errors are not captured. To do so, use APIExceptionManager(capture_validation=True)
instead.
from fastapi import FastAPI
from fastapi_routesmanager import RouteManagersRegistry, ManagedAPIRouter
from fastapi_exceptionshandler import APIExceptionManager
RouteManagersRegistry.register_route_manager(APIExceptionManager) # Register manager
app = FastAPI()
router = ManagedAPIRouter()
@router.get("/") # Use router instead of app
def read_root():
return 1/0
app.include_router(router) # Include the router to the app
Or you can handle exceptions manually...
from fastapi import FastAPI
from fastapi_exceptionshandler import APIExceptionHandler
app = FastAPI()
@app.get("/")
def read_root():
try:
return 1/0
except Exception as exc:
return await APIExceptionHandler.unhandled(exc)
Create a custom exception class and error code, then
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 create an Enum
class.
Note: if you want to capture only APIException
then use APIExceptionManager(capture_unhandled=False)
from enum import Enum
from fastapi import FastAPI
from fastapi_routesmanager import RouteManagersRegistry, ManagedAPIRouter
from fastapi_exceptionshandler import APIExceptionManager, APIException
RouteManagersRegistry.register_route_manager(APIExceptionManager) # Register manager
app = FastAPI()
router = ManagedAPIRouter()
class CustomException(APIException):
status_code = 401
class ErrorCode(Enum):
CustomExceptionCode = "Custom Exception Message"
@router.get("/") # Use router instead of app
def read_root():
raise CustomException(CustomException.ErrorCode.CustomExceptionCode)
app.include_router(router) # Include the router to the app
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
Hashes for fastapi_exceptionshandler-0.0.3.tar.gz
Algorithm | Hash digest | |
---|---|---|
SHA256 | f59f4160296851ef3a308324af0099e0b46a38a5c5ee586cd6ae78d1aa82842c |
|
MD5 | d779406b83a6ecec812e7e38f6c8c06d |
|
BLAKE2b-256 | f60c993c58cb7b543ffb8284c2558d2e3ec6d96fb2dcc226ea9b1eada70f7514 |
Hashes for fastapi_exceptionshandler-0.0.3-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 9f37417374b137ed171138baf3dc421424fed94b239b0ce6913b3a676c56a9f0 |
|
MD5 | 96e968ddf6ad16078596f1ac32ffa334 |
|
BLAKE2b-256 | da1ea0aaa080efd424a86ca73b63b278bf4e1b76bd9fdf32c03a9763d61ef09e |