Error Handlers ¶
Stario uses standard Python exceptions to manage errors. You can register global handlers to return custom HTML or JSON.
1. Registering Handlers ¶
Use app.on_error(ExceptionType, handler) to catch specific errors.
from stario import HttpException
def handle_404(c: Context, w: Writer, exc: HttpException):
w.status(404)
w.html(Div(H1("404"), P("Not Found")))
def handle_generic(c: Context, w: Writer, exc: Exception):
c["error"] = str(exc) # Log to tracer
w.json({"error": "Internal Server Error"}, status=500)
app.on_error(HttpException, handle_404)
app.on_error(Exception, handle_generic)
2. Raising Exceptions ¶
Raise exceptions anywhere in your handlers or business logic.
async def get_user(c: Context, w: Writer):
user = await db.find(c.req.tail)
if not user:
# Triggers the handle_404 registered above
raise HttpException(404, "User not found")
w.json(user)
3. Datastar-Aware Errors ¶
You can detect if a request came from Datastar and return a reactive signal instead of a full page.
def handle_validation(c: Context, w: Writer, exc: MyValidationError):
if c.req.headers.get("datastar-request") == "true":
w.sync({"error": str(exc)}) # Update error signal on client
else:
w.json({"error": str(exc)}, status=400)
Summary ¶
- Organization: Keep your error handlers in a separate
errors.pyand register them inmain.py. - Security: Never return raw exception strings to the client in production. Use the tracer (
c.span) to record the details for developers.
