# Routes Manager for FastAPI
Standardize and handle exceptions in [FastAPI](https://github.com/tiangolo/fastapi) more elegantly.
## Installation
```console
$ pip install fastapi-exceptionshandler
```
## Example
```python
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
```console
$ uvicorn main:app --reload
```
### Check it
Browse to http://127.0.0.1:8000 you should see this json:
```console
{"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`
```python
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
```console
{"errorCode": "CustomExceptionCode", "message": "Custom Exception Message"}
```
<details>
<summary>Or you can handle exceptions manually...</summary>
```python
@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)
```
</details>
**Note:** The `ErrorCode` class doesn't need to be inside `CustomException` and can be shared with another exceptions as well.
Raw data
{
"_id": null,
"home_page": null,
"name": "fastapi-exceptionshandler",
"maintainer": null,
"docs_url": null,
"requires_python": ">=3.7",
"maintainer_email": null,
"keywords": "fastapi, middleware, exception, error, handler, response, api",
"author": null,
"author_email": "SirPaulO <me@sirpauloliver.com>",
"download_url": "https://files.pythonhosted.org/packages/05/4b/912e914897361c860e9a1fcbd45ab380b44cfdaf0a36b0f4558ab5c2686e/fastapi_exceptionshandler-0.1.1.tar.gz",
"platform": null,
"description": "# Routes Manager for FastAPI\n\nStandardize and handle exceptions in [FastAPI](https://github.com/tiangolo/fastapi) more elegantly.\n\n## Installation\n\n```console\n$ pip install fastapi-exceptionshandler\n```\n\n\n## Example\n\n```python\nfrom fastapi import FastAPI\n\nfrom fastapi_exceptionshandler import APIExceptionMiddleware\n\napp = FastAPI()\n\n# Register the middleware\napp.add_middleware(APIExceptionMiddleware, capture_unhandled=True) # Capture all exceptions\n\n# You can also capture Validation errors, that are not captured by default\nfrom fastapi_exceptionshandler import APIExceptionHandler\n\nfrom pydantic import ValidationError\napp.add_exception_handler(ValidationError, APIExceptionHandler.unhandled)\n\nfrom fastapi.exceptions import RequestValidationError\napp.add_exception_handler(RequestValidationError, APIExceptionHandler.unhandled)\n\n@app.get(\"/\")\ndef read_root():\n return 1/0\n\n```\n\n\n### Run it\n\n```console\n$ uvicorn main:app --reload\n```\n\n### Check it\n\nBrowse to http://127.0.0.1:8000 you should see this json:\n\n```console\n{\"errorCode\": \"InternalError\", \"message\": \"Internal Server Error\"}\n```\n\n## Creating custom exceptions\n\nIn order to create a custom exception you need to extend `APIException` and `ErrorCodeBase` classes.\n\n**Note:** if you want to capture *only* `APIException` then don't send the `capture_unhandled` param, or set it to `False`\n\n```python\nfrom fastapi import FastAPI\n\nfrom fastapi_exceptionshandler import APIExceptionMiddleware, APIException, ErrorCodeBase\n\nfrom starlette import status\n\n\napp = FastAPI()\n\n# Register the middleware\napp.add_middleware(APIExceptionMiddleware)\n\n\nclass CustomException(APIException):\n status_code = status.HTTP_400_BAD_REQUEST\n \n class ErrorCode(ErrorCodeBase):\n CustomExceptionCode = \"Custom Exception Message\", status.HTTP_401_UNAUTHORIZED\n CustomExceptionCodeWithDefaultStatusCode = \"Custom Exception Message\"\n \n \n@app.get(\"/\")\ndef read_root():\n raise CustomException(CustomException.ErrorCode.CustomExceptionCode)\n\n```\n\nThen you should get a `401` response with this body\n\n```console\n{\"errorCode\": \"CustomExceptionCode\", \"message\": \"Custom Exception Message\"}\n```\n\n<details>\n<summary>Or you can handle exceptions manually...</summary>\n\n```python\n@app.get(\"/\")\ndef read_root():\n try:\n raise CustomException(CustomException.ErrorCode.CustomExceptionCode)\n except APIException as exc:\n return await APIExceptionHandler.handled(exc)\n except Exception as exc: # Handle all exceptions\n return await APIExceptionHandler.unhandled(exc)\n\n```\n</details>\n\n\n**Note:** The `ErrorCode` class doesn't need to be inside `CustomException` and can be shared with another exceptions as well.\n",
"bugtrack_url": null,
"license": "MIT License",
"summary": "Standardize and handle exceptions in FastAPI more elegantly",
"version": "0.1.1",
"project_urls": {
"Bug Tracker": "https://github.com/SirPaulO/fastapi_exceptionshandler/issues",
"Homepage": "https://github.com/SirPaulO/fastapi_exceptionshandler",
"Repository": "https://github.com/SirPaulO/fastapi_exceptionshandler.git"
},
"split_keywords": [
"fastapi",
" middleware",
" exception",
" error",
" handler",
" response",
" api"
],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "665ace02be1bb75af5b21d07ccf5b1dcd16ad13b9bf1c6d5ca44788376be4990",
"md5": "92b5d789bf8e1aa28754897dee9a8ae7",
"sha256": "004a5e9534142fa6b068f0ecd2fae84fedec061eeff1deb103bc23e5b6eec8a6"
},
"downloads": -1,
"filename": "fastapi_exceptionshandler-0.1.1-py3-none-any.whl",
"has_sig": false,
"md5_digest": "92b5d789bf8e1aa28754897dee9a8ae7",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": ">=3.7",
"size": 5844,
"upload_time": "2024-07-10T13:37:11",
"upload_time_iso_8601": "2024-07-10T13:37:11.455756Z",
"url": "https://files.pythonhosted.org/packages/66/5a/ce02be1bb75af5b21d07ccf5b1dcd16ad13b9bf1c6d5ca44788376be4990/fastapi_exceptionshandler-0.1.1-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": "",
"digests": {
"blake2b_256": "054b912e914897361c860e9a1fcbd45ab380b44cfdaf0a36b0f4558ab5c2686e",
"md5": "3be29e7784b9a8c0ac71b142a4f54044",
"sha256": "f93dd88da5e0e96fdddeaa86aaf9249fe73599e8e1e4d6c035030346bf545108"
},
"downloads": -1,
"filename": "fastapi_exceptionshandler-0.1.1.tar.gz",
"has_sig": false,
"md5_digest": "3be29e7784b9a8c0ac71b142a4f54044",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.7",
"size": 4559,
"upload_time": "2024-07-10T13:37:12",
"upload_time_iso_8601": "2024-07-10T13:37:12.483738Z",
"url": "https://files.pythonhosted.org/packages/05/4b/912e914897361c860e9a1fcbd45ab380b44cfdaf0a36b0f4558ab5c2686e/fastapi_exceptionshandler-0.1.1.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2024-07-10 13:37:12",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "SirPaulO",
"github_project": "fastapi_exceptionshandler",
"travis_ci": false,
"coveralls": false,
"github_actions": true,
"requirements": [
{
"name": "starlette",
"specs": [
[
"~=",
"0.27.0"
]
]
},
{
"name": "pydantic",
"specs": [
[
">=",
"1.10.7"
]
]
},
{
"name": "fastapi",
"specs": [
[
">=",
"0.95.2"
]
]
},
{
"name": "pre-commit",
"specs": [
[
"~=",
"3.4.0"
]
]
}
],
"lcname": "fastapi-exceptionshandler"
}