Skip to main content

Web based error utils

Project description

Web Errors v0.6.1

image image image style tests codecov

web_error is a set of exceptions and handlers for use in starlette/fastapi applications to support easy error management and responses

Each exception easily marshals to JSON based on the [RFC9457] spec for use in api errors.

Errors

The base web_error.error.HttpException accepts a title, details, status (default 500) and optional **kwargs. An additional code can be passed in, which will be used as the type, if not provided the type is derived from the class name.

And will render a json response with status as the status code:

{
    "type": "an-exception",
    "title": "title",
    "details": "details",
    "status": 500,
    "extra-key": "extra-value",
    ...
}

Derived types are generated using the class name after dropping ...Error from the end, and converting to kebab-case. i.e. PascalCaseError will derive the type pascal-case. If the class name doesn't suit your purposes, an optional code attribute can be set with the desired value of there response type field.

Some convenience Exceptions are provided with predefined status attributes. To create custom errors subclasss these and define the title attribute.

  • web_error.error.ServerException provides status 500 errors
  • web_error.error.BadRequestException provides status 400 errors
  • web_error.error.UnauthorisedException provides status 401 errors
  • web_error.error.NotFoundException provides status 404 errors

Custom Errors

Subclassing the convenience classes provide a simple way to consistently raise the same error with details/extras changing based on the raised context.

from web_error.error import NotFoundException


class UserNotFoundError(NotFoundException):
    title = "User not found."

raise UserNotFoundError(details="details")
{
    "type": "user-not-found",
    "title": "User not found",
    "details": "details",
    "status": 404,
}

Whereas a defined code will be used in the output.

class UserNotFoundError(NotFoundException):
    title = "User not found."
    code = "cant-find-user"

raise UserNotFoundError(details="details")
{
    "type": "cant-find-user",
    "title": "User not found",
    "details": "details",
    "status": 404,
}

If additional kwargs are provided when the error is raised, they will be included in the output (ensure the provided values are json seriablizable.

raise UserNotFoundError(details="details", user_id="1234", metadata={"hello": "world"})
{
    ...
    "details": "details",
    "user_id": "1234",
    "metadata": {"hello": "world"},
}

Starlette

    import starlette.applications
    import web_error.handler.starlette

    exception_handler = web_error.handler.starlette.generate_handler()

    return starlette.applications.Starlette(
        exception_handlers={
            Exception: exception_handler,
            HTTPException: exception_handler,
        },
    )

A custom logger can be provided to generate_handler(logger=...).

If you require cors headers, you can pass a web_error.cors.CorsConfiguration instance to generate_handler(cors=...).

generate_handler(
    cors=CorsConfiguration(
        allow_origins=["*"],
        allow_methods=["*"],
        allow_headers=["*"],
        allow_credentials=True,
    )
)

To handle unexpected errors provide unhandled_wrappers, a dict mapping http status code to HttpCodeException, the system key default is also accepted as the root wrapper for all unhandled exceptions.

If you wish to hide debug messaging from external users, strip_debug=True will log the debug message and remove it from the response.

    from web_error.error import HttpCodeException

    class NotFoundError(HttpCodeException):
        status = 404
        message = "Endpoint not found."

    exception_handler = web_error.handler.starlette.generate_handler(
        unhandled_wrappers={
            "404": NotFoundError,
        },
    )

FastAPI

The FastAPI handler is identical to the starlette handler with the additional handling of RequestValidationError.

    import fastapi
    import web_error.handler.fastapi

    exception_handler = web_error.handler.fastapi.generate_handler()

    return fastapi.FastAPI(
        exception_handlers={
            Exception: exception_handler,
            RequestValidationError: exception_handler,
            HTTPException: exception_handler,
        },
    )

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

web_error-0.6.1.tar.gz (11.7 kB view details)

Uploaded Source

Built Distribution

web_error-0.6.1-py3-none-any.whl (12.3 kB view details)

Uploaded Python 3

File details

Details for the file web_error-0.6.1.tar.gz.

File metadata

  • Download URL: web_error-0.6.1.tar.gz
  • Upload date:
  • Size: 11.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.7.1 CPython/3.11.6 Linux/6.7.1-zen1-1-zen

File hashes

Hashes for web_error-0.6.1.tar.gz
Algorithm Hash digest
SHA256 28f8d6fefcf577986d65dce6954b5c9e28eedf019299e373fbd8ccf094d62a2c
MD5 d7988d32697d99735060d0a0bbf1084c
BLAKE2b-256 e382e21b860756083b1736b6ac40e51cf9ab52b6a537db1509f0c4aa9127d951

See more details on using hashes here.

Provenance

File details

Details for the file web_error-0.6.1-py3-none-any.whl.

File metadata

  • Download URL: web_error-0.6.1-py3-none-any.whl
  • Upload date:
  • Size: 12.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.7.1 CPython/3.11.6 Linux/6.7.1-zen1-1-zen

File hashes

Hashes for web_error-0.6.1-py3-none-any.whl
Algorithm Hash digest
SHA256 ce52ed7f0162a999bb617ccf9c432c1776f61602827a25c1918037b8016e79f5
MD5 49e3afe6864ae5234f9ec3640347e349
BLAKE2b-256 20ac5cc447cc46c6af32597d654780562f48beb311e67474917b4882a6e13a0a

See more details on using hashes here.

Provenance

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