Skip to main content

A sample Python project

Project description

FastAPI Fancy Exceptions

Sample code

import uvicorn
from fastapi import FastAPI
from starlette import status
from starlette.requests import Request
from starlette.responses import JSONResponse
from src.fastapi_fancy_exceptions import FancyHTTPException


app = FastAPI()


class AuthException(FancyHTTPException):
    code = "auth_error"
    type = "AuthError"
    message = "Auth error"
    status_code = status.HTTP_401_UNAUTHORIZED


@app.exception_handler(FancyHTTPException)
async def http_exception_accept_handler(request: Request, exc: FancyHTTPException) -> JSONResponse:
    return JSONResponse(
        status_code=exc.status_code,
        content=[{"code": exc.code, "type": exc.type, "message": exc.message}]
    )


@app.get("/")
async def root():
    raise AuthException()

uvicorn.run(app, host="localhost", port=8000)

This code will lead to this response with status code 401:

[
  {
    "code": "auth_error",
    "type": "AuthError",
    "message": "Auth error"
  }
]

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-fancy-exceptions-0.0.3.tar.gz (6.4 kB view hashes)

Uploaded Source

Built Distribution

fastapi_fancy_exceptions-0.0.3-py3-none-any.whl (4.3 kB view hashes)

Uploaded Python 3

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