Error Handlers & Custom Exceptions
Define Custom Exceptions
class NotFound(Exception):
pass
class ValidationError(Exception):
pass
class UnauthorizedError(Exception):
pass
Register Exception Handlers
from stario import Stario
from stario.html import html, h1, p
from stario.responses import PlainTextResponse
app = Stario()
async def handle_not_found(request, exc):
return PlainTextResponse("Not Found", status_code=404)
async def handle_validation(request, exc):
return PlainTextResponse("Validation Error", status_code=400)
async def handle_unauthorized(request, exc):
return PlainTextResponse("Unauthorized", status_code=401)
app.add_exception_handler(NotFound, handle_not_found)
app.add_exception_handler(ValidationError, handle_validation)
app.add_exception_handler(UnauthorizedError, handle_unauthorized)
Raise in Endpoints
from stario import Query
from stario.html import html, head, body, h1
@app.query("/users/{user_id}")
async def get_user(user_id: int):
user = db.find_user(user_id)
if not user:
raise NotFound(f"User {user_id} not found")
return html(
head(),
body(
h1(user.name),
p(user.email),
)
)