Dobrý error handling = dobrý DX. Klient musí vědět co se stalo, proč a co s tím může dělat.
Error response format¶
// RFC 7807 — Problem Details { “type”: “https://api.example.com/errors/validation”, “title”: “Validation Error”, “status”: 422, “detail”: “Request body contains invalid fields”, “instance”: “/api/users”, “errors”: [ { “field”: “email”, “message”: “Invalid email format” }, { “field”: “age”, “message”: “Must be positive” } ] }
Implementace¶
FastAPI¶
from fastapi import HTTPException class AppError(HTTPException): def __init__(self, code: str, message: str, status: int = 400, details=None): super().__init__(status_code=status, detail={ “code”: code, “message”: message, “details”: details or [] }) @app.exception_handler(AppError) async def app_error_handler(request, exc): return JSONResponse(status_code=exc.status_code, content=exc.detail)
Klíčový takeaway¶
RFC 7807 pro standardní error format. Vždy code + message + details. Logujte na serveru, ne klientovi.