/py-pit:fastapi-errorsfrom py-pit
Standardizes error handling for FastAPI services with a single exception hierarchy, consistent JSON responses, and centralized logging for unexpected failures.
Ships in py-pit. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
Defines a simple, consistent error architecture for FastAPI backend services.
This skill standardizes the flow:
service/domain failure
→ application exception
→ global FastAPI exception handler
→ consistent JSON response
The goal is to prevent common FastAPI problems:
HTTPException raised deep in service logicApply when the user:
Do not apply when:
The fastapi-init skill scaffolds a minimal version of this class. This skill defines the complete pattern. If both are present, this skill's version is authoritative.
The service defines one base exception for intentional application failures.
Preferred naming pattern:
<PackageName>Error
Examples:
BillingError
UserServiceError
InventoryError
If the package name cannot be determined, use:
AppError
Define all exceptions in a single module. In fastapi-init projects this is core/exceptions.py. In other layouts, exceptions.py at the package root is typical. Do not scatter them across feature files.
Example base implementation:
class AppError(Exception):
status_code = 500
detail: str = "An unexpected error occurred."
def __init__(self, detail: str | None = None, status_code: int | None = None, **context):
self.detail = detail if detail is not None else self.__class__.detail
self.status_code = status_code if status_code is not None else self.__class__.status_code
self.context = context
super().__init__(self.detail)
def __str__(self) -> str:
return self.detail
Key characteristics:
detail default, overridable per-instance or per-subclass**context kwargs for structured loggingstatus_code and detail as class attributesApplication/domain errors should subclass the base error.
Example:
class UserNotFoundError(AppError):
status_code = 404
detail = "User not found."
def __init__(self, user_id: int):
super().__init__(f"User {user_id} not found", user_id=user_id)
Example usage in service code:
if user is None:
raise UserNotFoundError(user_id)
The API boundary converts internal exceptions into HTTP responses.
Example:
@app.exception_handler(AppError)
async def handle_app_error(request: Request, exc: AppError):
if exc.context:
logger.warning(
exc.detail,
extra={"error_context": exc.context, "status_code": exc.status_code},
)
return JSONResponse(
status_code=exc.status_code,
content={"detail": exc.detail},
)
The **context kwargs are for structured logging at the boundary, not for the client response. Use them to attach identifiers (e.g., user_id=123) that aid debugging without leaking internals.
Response format is intentionally simple:
{
"detail": "User 123 not found"
}
Unexpected exceptions should be handled consistently.
Use a fallback handler for uncaught exceptions:
@app.exception_handler(Exception)
async def handle_unexpected_error(request: Request, exc: Exception):
logger.exception(
"Unhandled exception",
extra={
"path": str(request.url.path),
"method": request.method,
"error_type": type(exc).__name__,
},
)
return JSONResponse(
status_code=500,
content={"detail": "An unexpected error occurred."},
)
This does three things:
Do not leak raw internal exception details to clients.
Log at minimum: request path, HTTP method, exception type, and correlation ID if the repo uses one. Follow existing structured logging conventions if present.
In existing repositories, inspect current error patterns before introducing new ones.
To find existing patterns, search for:
class.*Error(Exception) or class.*Exception(Exception) in the packageexception_handler registrations in the app factory or main moduleHTTPException usage in service or domain code (a signal that the boundary is leaking)Then follow these rules:
Do not create parallel exception hierarchies in a mature codebase.
FastAPI raises RequestValidationError for malformed or invalid request bodies. This is framework-level — it does not subclass your app's base exception. Without a handler, FastAPI emits its default 422 response with a raw Pydantic error blob, which breaks response shape consistency.
Add a dedicated handler:
from fastapi.exceptions import RequestValidationError
@app.exception_handler(RequestValidationError)
async def handle_validation_error(request: Request, exc: RequestValidationError):
return JSONResponse(
status_code=422,
content={"detail": "Invalid request data", "details": exc.errors()},
)
Including exc.errors() in a details field is recommended — validation errors are client-fixable and surfacing them helps the caller correct the request.
Auth handling involves two distinct cases. Don't conflate them.
FastAPI security dependencies (HTTPBearer, OAuth2PasswordBearer, Depends(security_scheme), etc.) raise HTTPException internally. This is expected framework behavior — do not fight it or try to wrap it in domain exceptions.
Custom auth logic (token validation, permission checks) belongs in service code and should use domain exceptions:
class UnauthenticatedError(AppError):
status_code = 401
def __init__(self):
super().__init__("Authentication required")
class UnauthorizedError(AppError):
status_code = 403
def __init__(self, action: str | None = None):
msg = f"Not authorized to {action}" if action else "Not authorized"
super().__init__(msg)
These flow through the global AppError handler like any other domain exception.
For APIs consumed by clients that need to branch on error type — public APIs, client SDKs, multi-error workflows — a machine-readable code field is useful. Skip this for internal services or simple CRUD APIs where string parsing is acceptable.
Pattern: add an optional code class attribute to the existing base exception; domain subclasses override it. This extends the base class from the Base Exception section - do not redefine it.
class AppError(Exception):
status_code = 500
detail: str = "An unexpected error occurred."
code: str | None = None # add this to the existing base
...
Subclasses set a value:
class UserNotFoundError(AppError):
status_code = 404
code = "user_not_found"
...
Update the global handler to include code when present:
@app.exception_handler(AppError)
async def handle_app_error(request: Request, exc: AppError):
content = {"detail": exc.detail}
if exc.code:
content["code"] = exc.code
return JSONResponse(status_code=exc.status_code, content=content)
Response shape when code is set:
{
"detail": "User 123 not found",
"code": "user_not_found"
}
MUST
status_code on exception classes.RequestValidationError handler when response shape consistency matters.MUST NOT
HTTPException in service or domain code. Exception: HTTPException raised internally by FastAPI security dependencies (HTTPBearer, OAuth2PasswordBearer, etc.) is acceptable — that is the framework's designed behavior.ValueError, RuntimeError, etc.) for intentional domain failures.Applying this skill results in:
What SKILL.md sets; muted values are Claude Code's defaults
Generated from the plugin's indexed repository (robhowley/py-pit-skills) — no native marketplace selected
npx claudepluginhub p/robhowley-py-pit16 skills in this plugin
/alembic-migrationsProduction-safe Alembic migration workflows for SQLAlchemy 2.x projects. Use this skill when adding Alembic, generating migrations, reviewing autogenerate diffs, fixing broken migrations, or establishing a safe schema evolution workflow in a Python backend./background-jobs-boundariesGuardrails for background work in FastAPI and Python services. Prevent misuse of in-process background execution (e.g. FastAPI BackgroundTasks)./click-cliDesign, generate, and improve Python CLIs using the Click library. Focus on idiomatic architecture, command groups, modular layouts, CLI UX conventions, and avoiding common Click anti-patterns./click-cli-linterAudit and improve existing Python Click CLIs by identifying architecture problems, anti-patterns, and CLI UX issues, then proposing minimal, high-value fixes./code-qualityOpinionated code health stack for Python repos using Ruff, pre-commit, and Markdown linting. Prefers consolidation over redundant tooling, preserves working repos unless migration is requested, and provides a simple adoption path for both new and existing projects./dockerize-serviceGenerate a local-development Docker Compose setup for an existing Python project. Produces a multi-stage Dockerfile, Compose file, env config, and dockerignore based on detected project signals.Other plugins' skills for the same job