error-handling
БесплатноЗапускает вложенные скриптыНе проверенUse when implementing structured error handling in backend or frontend code. Triggers for: try-catch patterns, custom exception classes, global error…
от aiskillstore★ 509 звёзд на GitHubОб этом скилле
Error Handling Skill
Expert structured error handling for FastAPI backends and React/Next.js frontends with consistent error messages and logging.
Quick Reference
| Pattern | Backend | Frontend |
|---|---|---|
| Custom exception | class FeeNotPaidError(AppException) |
N/A |
| Try-catch | try: ... except SpecificError: |
try { } catch (e) { } |
| Global handler | @app.exception_handler |
ErrorBoundary component |
| User message | detail field in response |
Toast/Snackbar |
| Error logging | logger.error(...) |
Console/Sentry |
Custom Exceptions (Backend)
Base Exception Hierarchy
# backend/app/errors/exceptions.py
from fastapi import HTTPException
from typing import Any
class AppException(HTTPException):
"""Base application exception with user-friendly messages."""
def __init__(
self,
status_code: int,
detail: str,
user_message: str,
headers: dict[str, Any] | None = None,
):
self.user_message = user_message
super().__init__(status_code=status_code, detail=detail, headers=headers)
class NotFoundError(AppException):
"""Resource not found (404)."""
def __init__(self, resource: str, identifier: str):
super().__init__(
status_code=404,
detail=f"{resource} with id '{identifier}' not found",
user_message=f"{resource} not found. Please check and try again.",
)
class ValidationError(AppException):
"""Validation failed (400)."""
def __init__(self, field: str, reason: str):
super().__init__(
status_code=400,
detail=f"Validation error for field '{field}': {reason}",
user_message=f"Invalid value for {field}. {reason}",
)
class UnauthorizedError(AppException):
"""Authentication required (401)."""
def __init__(self, reason: str = "Authentication required"):
super().__init__(
status_code=401,
detail=reason,
user_message="Please log in to continue.",
headers={"WWW-Authenticate": "Bearer"},
)
class ForbiddenError(AppException):
"""Permission denied (403)."""
def __init__(self, action: str):
super().__init__(
status_code=403,
detail=f"Permission denied for action: {action}",
user_message=f"You don't have permission to {action}.",
)
class ConflictError(AppException):
"""Resource conflict (409)."""
def __init__(self, resource: str, reason: str):
super().__init__(
status_code=409,
detail=f"Conflict for {resource}: {reason}",
user_message=f"{resource} conflict. {reason}",
)
class RateLimitError(AppException):
"""Too many requests (429)."""
def __init__(self, retry_after: int = 60):
super().__init__(
status_code=429,
detail=f"Rate limit exceeded. Retry after {retry_after} seconds.",
user_message="Too many requests. Please wait a moment and try again.",
headers={"Retry-After": str(retry_after)},
)
Domain-Specific Exceptions
# backend/app/errors/domains.py
from .exceptions import NotFoundError, ValidationError, ConflictError
class StudentNotFoundError(NotFoundError):
def __init__(self, student_id: int):
super().__init__(resource="Student", identifier=str(student_id))
class FeeNotPaidError(ConflictError):
def __init__(self, student_id: int, amount_due: float):
super().__init__(
resource="Fee",
reason=f"Student {student_id} has unpaid fee of ${amount_due:.2f}",
)
class AttendanceAlreadyMarkedError(ConflictError):
def __init__(self, student_id: int, date: str):
super().__init__(
resource="Attendance",
reason=f"Attendance already marked for student {student_id} on {date}",
)
class InvalidGradeError(ValidationError):
def __init__(self, grade: str, valid_grades: list[str]):
super().__init__(
field="grade",
reason=f"'{grade}' is not valid. Must be one of: {', '.join(valid_grades)}",
)
class InsufficientBalanceError(ValidationError):
def __init__(self, required: float, available: float):
super().__init__(
field="amount",
reason=f"Insufficient balance. Required: ${required:.2f}, Available: ${available:.2f}",
)
Try-Catch Patterns
Narrow Try Blocks
# GOOD: Specific exception, narrow scope
try:
student = await get_student_by_id(student_id)
except StudentNotFoundError:
raise StudentNotFoundError(student_id)
# BAD: Too broad, catches everything
try:
student = await get_student_by_id(student_id)
calculate_fees(student)
send_notification(student)
update_records(student)
except Exception:
pass # Swallowed!
Cleanup with Finally
import asyncio
Установить error-handling в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
FAQ
Что делает скилл error-handling?
Use when implementing structured error handling in backend or frontend code. Triggers for: try-catch patterns, custom exception classes, global error handlers, error logging, user-friendly error messages, or API error responses. NOT for: business logic validation (use domain exceptions) or unrelated error types.
Как установить скилл error-handling?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл error-handling запускает скрипты?
Да, скилл несёт исполняемые скрипты. Проверь исходник перед установкой.
Похожие скиллы
mcp-builder
Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
от Anthropicclaude-api
Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
от Anthropicalgorithmic-art
Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
от Anthropicmcp-integration
This skill should be used when the user asks to "add MCP server", "integrate MCP", "configure MCP in plugin", "use .mcp.json", "set up Model Context…
от Anthropic