Claude-skill-registry fastapi-error-handling
Provides a comprehensive, reusable skill for standardized API error handling in FastAPI. Includes custom exception classes, global exception handlers, structured JSON logging, and standardized Pydantic error schemas. Use this when you need to implement a robust error handling system in a FastAPI project.
git clone https://github.com/majiayu000/claude-skill-registry
T=$(mktemp -d) && git clone --depth=1 https://github.com/majiayu000/claude-skill-registry "$T" && mkdir -p ~/.claude/skills && cp -r "$T/skills/data/fastapi-error-handling" ~/.claude/skills/majiayu000-claude-skill-registry-fastapi-error-handling && rm -rf "$T"
skills/data/fastapi-error-handling/SKILL.mdFastAPI Error Handling Skill
This skill provides a structured and reusable approach to handling exceptions in a FastAPI application. It includes custom exceptions, global handlers, structured logging, and standardized response schemas.
Core Components
The implementation is split across four reference files for clarity and modularity. You should create a new module in your project (e.g.,
my_app/error_handling/) and place these files within it. Remember to add an empty __init__.py in that directory to make it a Python package.
: Contains a hierarchy of custom exception classes that can be raised from your application logic.references/exceptions.py
: Defines the Pydantic models for standardized error responses.references/schemas.py
: Provides global exception handler functions to catch custom and unhandled exceptions, format the response, and log the error.references/handlers.py
: Includes a configuration for structured JSON logging, which is crucial for monitoring and debugging in production.references/logging_config.py
How to Use
Step 1: Integrate the Components
- Create a new package in your FastAPI project (e.g.,
).my_project/error_handling - Copy the content from the following files into the corresponding new files within your
package:error_handling
->references/exceptions.pymy_project/error_handling/exceptions.py
->references/schemas.pymy_project/error_handling/schemas.py
->references/handlers.pymy_project/error_handling/handlers.py
->references/logging_config.pymy_project/error_handling/logging_config.py
- Create an empty
file.my_project/error_handling/__init__.py - The logging configuration in
requireslogging_config.py
. Install it:python-json-loggerpip install python-json-logger
Step 2: Configure Your FastAPI App
In your main application file (e.g.,
main.py), import and apply the configurations.
from fastapi import FastAPI from my_project.error_handling.handlers import register_exception_handlers from my_project.error_handling.logging_config import setup_logging # Apply structured logging configuration setup_logging() app = FastAPI() # Register the global exception handlers register_exception_handlers(app) # ... your routes and other application logic
Step 3: Use in Your Application
Now you can raise the custom exceptions from your API endpoints. The global handlers will automatically catch them and return a standardized JSON response.
Example:
from fastapi import APIRouter from my_project.error_handling.exceptions import NotFound, Unauthorized router = APIRouter() @router.get("/items/{item_id}") async def read_item(item_id: int): if item_id == 42: # This will be caught by the api_exception_handler raise NotFound(message=f"Item with id {item_id} does not exist.") if item_id == 13: # This will also be caught raise Unauthorized(user_message="You do not have permission to view this sacred item.") return {"item_id": item_id} @router.get("/unhandled") async def trigger_unhandled_error(): # This will be caught by the unhandled_exception_handler result = 1 / 0 return {"result": result} app.include_router(router)
Customization
- Environment: The
file uses a simplehandlers.py
flag. In a real application, you should replace this with a proper settings management system (e.g., Pydantic'sIS_DEV_ENVIRONMENT
) to control whether debug information is included in responses.BaseSettings - Exceptions: You can easily extend
with more specific exception classes inheriting fromexceptions.py
.APIException