fastapi-exceptionshandler


Namefastapi-exceptionshandler JSON
Version 0.1.0 PyPI version JSON
download
home_pageNone
SummaryStandardize and handle exceptions in FastAPI more elegantly
upload_time2024-04-25 19:26:30
maintainerNone
docs_urlNone
authorNone
requires_python>=3.7
licenseMIT License
keywords fastapi middleware exception error handler response api
VCS
bugtrack_url
requirements No requirements were recorded.
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/96/9c/98102fa66ccf1254665284cf0b31d54e2f1bf493b380807749208dc1769e/fastapi_exceptionshandler-0.1.0.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.0",
    "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": "3b24472525b255b014aa97194bda63a934b6b6376656ec2931aee2e593de8942",
                "md5": "0c1f992a480bb252743705d525a8dc49",
                "sha256": "cd1c5e5da4beff36a959d0e5976ec67fd6c53b5d86eb936233fe0fe85b703d71"
            },
            "downloads": -1,
            "filename": "fastapi_exceptionshandler-0.1.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "0c1f992a480bb252743705d525a8dc49",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.7",
            "size": 5778,
            "upload_time": "2024-04-25T19:26:29",
            "upload_time_iso_8601": "2024-04-25T19:26:29.652281Z",
            "url": "https://files.pythonhosted.org/packages/3b/24/472525b255b014aa97194bda63a934b6b6376656ec2931aee2e593de8942/fastapi_exceptionshandler-0.1.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "969c98102fa66ccf1254665284cf0b31d54e2f1bf493b380807749208dc1769e",
                "md5": "2a16be8e344cd2576d7bfcee02542750",
                "sha256": "303af870ed82aaf074a2d2200fa9b9f4fd145f782f5bddd3599d2b3c01c8937f"
            },
            "downloads": -1,
            "filename": "fastapi_exceptionshandler-0.1.0.tar.gz",
            "has_sig": false,
            "md5_digest": "2a16be8e344cd2576d7bfcee02542750",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.7",
            "size": 4507,
            "upload_time": "2024-04-25T19:26:30",
            "upload_time_iso_8601": "2024-04-25T19:26:30.749144Z",
            "url": "https://files.pythonhosted.org/packages/96/9c/98102fa66ccf1254665284cf0b31d54e2f1bf493b380807749208dc1769e/fastapi_exceptionshandler-0.1.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-04-25 19:26:30",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "SirPaulO",
    "github_project": "fastapi_exceptionshandler",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "requirements": [],
    "lcname": "fastapi-exceptionshandler"
}
        
Elapsed time: 0.28321s