Good error handling = good DX. The client must know what happened, why, and what they can do about it.
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” } ] }
Implementation¶
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)
Key Takeaway¶
RFC 7807 for a standard error format. Always include code + message + details. Log on the server, not on the client.