Skip to main content

Fastapi errors module.

Project description

Example of using exceptions schema generator for FastAPI.

from abc import abstractproperty
from typing import Optional
from fastapi import FastAPI
from fastapi_errors.exceptions import DefaultHTTPException, BaseHTTPException
from fastapi_errors.generator import generate_examples, ExamplesGenerator
from starlette.responses import JSONResponse

app = FastAPI()


class NotAuthorized(DefaultHTTPException):
    error = "UNAUTHORIZED"
    status_code = 401
    message = "Not authorized."
    field = None


class StaffOnly(DefaultHTTPException):
    error = "STAFF_ONLY"
    status_code = 401
    message = "Staff only."
    field = None


@app.get(
    "/",
    responses=generate_examples(
        NotAuthorized
    )
)
async def get():
    pass


class CustomException(BaseHTTPException):
    """Custom class for all HTTP exceptions."""

    error: str = abstractproperty()
    message: str = abstractproperty()
    field: Optional[str] = abstractproperty()
    item_id: int = abstractproperty()

    def __init__(
        self,
        item_id: Optional[int] = None,
        message: Optional[str] = None,
        field: Optional[str] = None
    ) -> None:
        """Initialize the exception."""
        self.message = message if message else self.message
        self.field = field if field else self.field
        self.item_id = item_id
        super().__init__()

    def example(self) -> dict:
        """Return an example of the error response. This is used in the OpenAPI docs."""
        # create details
        details = {
            "field": "string",
            "message": self.message,
            "item_id": self.item_id,
        }
        # create example
        example = {
            "summary": self.error,
            "value": {
                "status": self.status_code,
                "error": {"code": self.error, "details": details},
            },
        }
        return example


@app.exception_handler(CustomException)
async def custom_exception_handler(request, exc):
    return JSONResponse(
        status_code=exc.status_code,
        content={
            "status": exc.status_code,
            "code": exc.error,
            "details": {
                "message": str(exc.message),
                "field": exc.field,
                "item_id": exc.item_id,
            },
        },
    )


class MyException(CustomException):
    """Custom exception class."""

    error = "MY_ERROR"
    message = "My error message."
    item_id = 1
    field = None


class CustomExamplesGenerator(ExamplesGenerator):
    """Custom examples generator."""

    default_exceptions = (
        NotAuthorized,
    )

    staff = (
        StaffOnly,
    )


generate_examples = CustomExamplesGenerator.generate_examples


@app.get(
    "/{item_id}",
    responses=generate_examples(
        MyException,
        add=["staff"]
    )
)
async def get_item(item_id: int):
    raise MyException(item_id=item_id, field="burger")

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

fastapi_errors-0.0.5.tar.gz (5.2 kB view details)

Uploaded Source

Built Distribution

fastapi_errors-0.0.5-py2.py3-none-any.whl (4.9 kB view details)

Uploaded Python 2 Python 3

File details

Details for the file fastapi_errors-0.0.5.tar.gz.

File metadata

  • Download URL: fastapi_errors-0.0.5.tar.gz
  • Upload date:
  • Size: 5.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: python-requests/2.32.3

File hashes

Hashes for fastapi_errors-0.0.5.tar.gz
Algorithm Hash digest
SHA256 7fa312aff17b73d794ff9f9ce6080f6ffeadaf7174dc01276df23cf70e70eb87
MD5 b42709143abd899ab810081e67d45aed
BLAKE2b-256 c7f95e6236845ab0fac626e6c9d3d24df38b59c51a1614185456c6029fc7f9c7

See more details on using hashes here.

File details

Details for the file fastapi_errors-0.0.5-py2.py3-none-any.whl.

File metadata

File hashes

Hashes for fastapi_errors-0.0.5-py2.py3-none-any.whl
Algorithm Hash digest
SHA256 f4d0f1725841d6c429815b17978410a97004d864864f7b25afb6a85cee484679
MD5 f58b3cc460b59908179c8d8d49fc70b7
BLAKE2b-256 72435a7adddeb453475045074207af717676c20139bb0c0dc0ac172d6032fa4b

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page