| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
from dataclasses import dataclass |
| 4 |
|
| 5 |
from litestar import Litestar, post |
| 6 |
from litestar.plugins.problem_details import ProblemDetailsConfig, ProblemDetailsException, ProblemDetailsPlugin |
| 7 |
|
| 8 |
|
| 9 |
@dataclass |
| 10 |
class PurchaseItem: |
| 11 |
item_id: int |
| 12 |
quantity: int |
| 13 |
|
| 14 |
|
| 15 |
class PurchaseNotAllowedError(Exception): |
| 16 |
def __init__(self, account_id: int, balance: int, detail: str) -> None: |
| 17 |
self.account_id = account_id |
| 18 |
self.balance = balance |
| 19 |
self.detail = detail |
| 20 |
|
| 21 |
|
| 22 |
@post("/purchase") |
| 23 |
async def purchase(data: PurchaseItem) -> None: |
| 24 |
raise PurchaseNotAllowedError( |
| 25 |
account_id=12345, |
| 26 |
balance=30, |
| 27 |
detail="Your current balance is 30, but that costs 50.", |
| 28 |
) |
| 29 |
|
| 30 |
|
| 31 |
def convert_purchase_not_allowed_to_problem_details(exc: PurchaseNotAllowedError) -> ProblemDetailsException: |
| 32 |
return ProblemDetailsException( |
| 33 |
type_="https://example.com/probs/out-of-credit", |
| 34 |
title="You do not have enough credit.", |
| 35 |
detail=exc.detail, |
| 36 |
instance=f"/account/{exc.account_id}/msgs/abc", |
| 37 |
extra={"balance": exc.balance}, |
| 38 |
) |
| 39 |
|
| 40 |
|
| 41 |
problem_details_plugin = ProblemDetailsPlugin( |
| 42 |
ProblemDetailsConfig( |
| 43 |
enable_for_all_http_exceptions=True, |
| 44 |
exception_to_problem_detail_map={PurchaseNotAllowedError: convert_purchase_not_allowed_to_problem_details}, |
| 45 |
) |
| 46 |
) |
| 47 |
app = Litestar(route_handlers=[purchase], plugins=[problem_details_plugin]) |
| 48 |
|
| 49 |
# run: /purchase --header "Content-Type: application/json" --request POST --data '{"item_id": 1234, "quantity": 2}' |