fastapi-exceptionshandler


Namefastapi-exceptionshandler JSON
Version 0.1.2 PyPI version JSON
download
home_pageNone
SummaryStandardize and handle exceptions in FastAPI more elegantly
upload_time2025-01-02 17:10:51
maintainerNone
docs_urlNone
authorNone
requires_python>=3.7
licenseMIT License
keywords fastapi middleware exception error handler response api
VCS
bugtrack_url
requirements starlette pydantic fastapi pre-commit fastapi-routesmanager
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # 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/4d/c8/a15fb3bcea590594f158d5c9c0c52c4dddc42ff8b2ace0df0d8589b314ba/fastapi_exceptionshandler-0.1.2.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.2",
    "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": "60989b625af88f8be076bf70b0eb1551f4700ca6cdf7210020317a6bea5bbbe7",
                "md5": "9ea2d972b9438b14402163e06646239e",
                "sha256": "a593c8665826d6e93e03e1130e31d2708952664a044d961b83ec8372998b025e"
            },
            "downloads": -1,
            "filename": "fastapi_exceptionshandler-0.1.2-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "9ea2d972b9438b14402163e06646239e",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.7",
            "size": 5932,
            "upload_time": "2025-01-02T17:10:48",
            "upload_time_iso_8601": "2025-01-02T17:10:48.853983Z",
            "url": "https://files.pythonhosted.org/packages/60/98/9b625af88f8be076bf70b0eb1551f4700ca6cdf7210020317a6bea5bbbe7/fastapi_exceptionshandler-0.1.2-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "4dc8a15fb3bcea590594f158d5c9c0c52c4dddc42ff8b2ace0df0d8589b314ba",
                "md5": "f16dccbb7f736d90f2c50fc49fd2a4c7",
                "sha256": "feff01ca835d6d0f8b60f8a229b083d63ceffee0aa0aa0705ff07b2da6b1ee48"
            },
            "downloads": -1,
            "filename": "fastapi_exceptionshandler-0.1.2.tar.gz",
            "has_sig": false,
            "md5_digest": "f16dccbb7f736d90f2c50fc49fd2a4c7",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.7",
            "size": 4641,
            "upload_time": "2025-01-02T17:10:51",
            "upload_time_iso_8601": "2025-01-02T17:10:51.099652Z",
            "url": "https://files.pythonhosted.org/packages/4d/c8/a15fb3bcea590594f158d5c9c0c52c4dddc42ff8b2ace0df0d8589b314ba/fastapi_exceptionshandler-0.1.2.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-01-02 17:10:51",
    "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"
                ]
            ]
        },
        {
            "name": "fastapi-routesmanager",
            "specs": [
                [
                    ">=",
                    "0.0.3"
                ]
            ]
        }
    ],
    "lcname": "fastapi-exceptionshandler"
}
        
Elapsed time: 4.94111s