跳到主内容
智客 ZICQ

技能库 智客分类:设计创意 error-handling

Error Handling

跨 TypeScript 、 Python 和 Go 的稳健错误处理模式。 覆盖输入的错误、 错误边界、 重试、 断路器、 以及用户显示的错误信息 。 在TypeScript, Python, 或 Go 中设计出错误类型, 重试, 断路器, 或用户化失败消息时使用 .

8695 安装量

官方网址:skills.sh

技能介绍

先看中文介绍;官方 description 原文单独保留,不改写 SKILL.md。

做什么

横跨 TypeScript 、 Python 和 Go 的稳健错误处理模式。 覆盖输入错误、 错误边界、 重试、 断路器、 以及显示用户的错误信息

何时用

在 TypeScript 、 Python 或 Go 中设计出出错类型、 复写器、 断路器或用户显示的故障信息

代理如何加载

按 Agent Skills 渐进披露:启动时只加载 name 与 description(约 100 token);任务匹配后才读入整份 SKILL.md 正文;scripts/、references/、assets/ 仅在需要时再读。 本文件正文结构:Error Handling Patterns、When to Activate、Core Principles、TypeScript / JavaScript、Typed Error Classes、Result Pattern (no-throw style)。

文件分析

文件分析:这是一份仅含 SKILL.md 的指令型技能,代理激活后整份正文进入上下文。

官方 description(原文)

Patterns for robust error handling across TypeScript, Python, and Go. Covers typed errors, error boundaries, retries, circuit breakers, and user-facing error messages. Use when designing error types, retries, circuit breakers, or user-facing failure messages in TypeScript, Python, or Go.

Error Handling PatternsWhen to ActivateCore PrinciplesTypeScript / JavaScriptTyped Error ClassesResult Pattern (no-throw style)API Error Handler (Next.js / Express)React Error BoundaryPythonCustom Exception HierarchyFastAPI Global Exception HandlerGo

来源分类:skills.sh agent-skill

SKILL.md 与 Agent 调用

官方规范 ↗
name
error-handling
description
Patterns for robust error handling across TypeScript, Python, and Go. Covers typed errors, error boundaries, retries, circuit breakers, and user-facing error messages. Use when designing error types, retries, circuit breakers, or user-facing failure messages in TypeScript, Python, or Go.
  1. 发现技能客户端向 Agent 提供名称与描述目录。
  2. 匹配与调用用户指定或任务匹配后,载入 SKILL.md 指令。
  3. 按需加载按步骤读取参考文档、使用脚本与素材。

具体调用语法与可用工具以目标 Agent 客户端为准。 查看调用机制说明 ↗

安装这个技能

Skills CLI ↗

先选择目标 Agent 和安装范围,保留技能包的附属文件,安装后检查客户端能否发现该技能。

交给 Agent 安装

复制安装指令给支持 Agent Skills 的代理,确认其中的目标目录与客户端匹配。

把 Agent Skill「error-handling」安装到我的项目:SKILL.md 原文与官方 description 见 https://zicq.com/zh/skills/skl-c63e5c450e2ee8eb-Error-Handling.html
请存为 .cursor/skills/error-handling/SKILL.md 或 .claude/skills/error-handling/SKILL.md,frontmatter 的 name 与 description 保持原样,不要改写。

GitHub 完整包 ↗

终端安装 · Skills CLI

需要 Node.js 与 npx。先查看仓库技能列表,确认实际名称。

npx skills add 'https://github.com/affaan-m/ecc' --list

npx skills add 'https://github.com/affaan-m/ecc' --skill 'error-handling'

CLI 会交互选择目标 Agent,默认安装到项目;用户级安装使用 -g。先通过查看命令核对仓库内容,再用 npx skills list 检查已安装技能。

阅读排版
--- name: error-handling description: Patterns for robust error handling across TypeScript, Python, and Go. Covers typed errors, error boundaries, retries, circuit breakers, and user-facing error messages. Use when designing error types, retries, circuit breakers, or user-facing failure messages in TypeScript, Python, or Go. metadata: origin: ECC --- # Error Handling Patterns Consistent, robust error handling patterns for production applications. ## When to Activate - Designing error types or exception hierarchies for a new module or service - Adding retry logic or circuit breakers for unreliable external dependencies - Reviewing API endpoints for missing error handling - Implementing user-facing error messages and feedback - Debugging cascading failures or silent error swallowing ## Core Principles 1. **Fail fast and loudly** — surface errors at the boundary where they occur; don't bury them 2. **Typed errors over string messages** — errors are first-class values with structure 3. **User messages ≠ developer messages** — show friendly text to users, log full context server-side 4. **Never swallow errors silently** — every `catch` block must either handle, re-throw, or log 5. **Errors are part of your API contract** — document every error code a client may receive ## TypeScript / JavaScript ### Typed Error Classes ```typescript // Define an error hierarchy for your domain export class AppError extends Error { constructor( message: string, public readonly code: string, public readonly statusCode: number = 500, public readonly details?: unknown, ) { super(message) this.name = this.constructor.name // Maintain correct prototype chain in transpiled ES5 JavaScript. // Required for `instanceof` checks (e.g., `error instanceof NotFoundError`) // to work correctly when extending the built-in Error class. Object.setPrototypeOf(this, new.target.prototype) } } export class NotFoundError extends AppError { constructor(resource: string, id: string) { super(`${resource} not found: ${id}`, 'NOT_FOUND', 404) } } export class ValidationError extends AppError { constructor(message: string, details: { field: string; message: string }[]) { super(message, 'VALIDATION_ERROR', 422, details) } } export class UnauthorizedError extends AppError { constructor(reason = 'Authentication required') { super(reason, 'UNAUTHORIZED', 401) } } export class RateLimitError extends AppError { constructor(public readonly retryAfterMs: number) { super('Rate limit exceeded', 'RATE_LIMITED', 429) } } ``` ### Result Pattern (no-throw style) For operations where failure is expected and common (parsing, external calls): ```typescript type Result = | { ok: true; value: T } | { ok: false; error: E } function ok(value: T): Result { return { ok: true, value } } function err(error: E): Result { return { ok: false, error } } // Usage async function fetchUser(id: string): Promise> { try { const user = await db.users.findUnique({ where: { id } }) if (!user) return err(new NotFoundError('User', id)) return ok(user) } catch (e) { return err(new AppError('Database error', 'DB_ERROR')) } } const result = await fetchUser('abc-123') if (!result.ok) { // TypeScript knows result.error here logger.error('Failed to fetch user', { error: result.error }) return } // TypeScript knows result.value here console.log(result.value.email) ``` ### API Error Handler (Next.js / Express) ```typescript import { NextRequest, NextResponse } from 'next/server' function handleApiError(error: unknown): NextResponse { // Known application error if (error instanceof AppError) { return NextResponse.json( { error: { code: error.code, message: error.message, ...(error.details ? { details: error.details } : {}), }, }, { status: error.statusCode }, ) } // Zod validation error if (error instanceof z.ZodError) { return NextResponse.json( { error: { code: 'VALIDATION_ERROR', message: 'Request validation failed', details: error.issues.map(i => ({ field: i.path.join('.'), message: i.message, })), }, }, { status: 422 }, ) } // Unexpected error — log details, return generic message console.error('Unexpected error:', error) return NextResponse.json( { error: { code: 'INTERNAL_ERROR', message: 'An unexpected error occurred' } }, { status: 500 }, ) } export async function POST(req: NextRequest) { try { // ... handler logic } catch (error) { return handleApiError(error) } } ``` ### React Error Boundary ```typescript import { Component, ErrorInfo, ReactNode } from 'react' interface Props { fallback: ReactNode onError?: (error: Error, info: ErrorInfo) => void children: ReactNode } interface State { hasError: boolean error: Error | null } export class ErrorBoundary extends Component { state: State = { hasError: false, error: null } static getDerivedStateFromError(error: Error): State { return { hasError: true, error } } componentDidCatch(error: Error, info: ErrorInfo) { this.props.onError?.(error, info) console.error('Unhandled React error:', error, info) } render() { if (this.state.hasError) return this.props.fallback return this.props.children } } // Usage Something went wrong. Please refresh.

}> ``` ## Python ### Custom Exception Hierarchy ```python class AppError(Exception): """Base application error.""" def __init__(self, message: str, code: str, status_code: int = 500): super().__init__(message) self.code = code self.status_code = status_code class NotFoundError(AppError): def __init__(self, resource: str, id: str): super().__init__(f"{resource} not found: {id}", "NOT_FOUND", 404) class ValidationError(AppError): def __init__(self, message: str, details: list[dict] | None = None): super().__init__(message, "VALIDATION_ERROR", 422) self.details = details or [] ``` ### FastAPI Global Exception Handler ```python from fastapi import FastAPI, Request from fastapi.responses import JSONResponse app = FastAPI() @app.exception_handler(AppError) async def app_error_handler(request: Request, exc: AppError) -> JSONResponse: return JSONResponse( status_code=exc.status_code, content={"error": {"code": exc.code, "message": str(exc)}}, ) @app.exception_handler(Exception) async def generic_error_handler(request: Request, exc: Exception) -> JSONResponse: # Log full details, return generic message logger.exception("Unexpected error", exc_info=exc) return JSONResponse( status_code=500, content={"error": {"code": "INTERNAL_ERROR", "message": "An unexpected error occurred"}}, ) ``` ## Go ### Sentinel Errors and Error Wrapping ```go package domain import "errors" // Sentinel errors for type-checking var ( ErrNotFound = errors.New("not found") ErrUnauthorized = errors.New("unauthorized") ErrConflict = errors.New("conflict") ) // Wrap errors with context — never lose the original func (r *UserRepository) FindByID(ctx context.Context, id string) (*User, error) { user, err := r.db.QueryRow(ctx, "SELECT * FROM users WHERE id = $1", id) if errors.Is(err, sql.ErrNoRows) { return nil, fmt.Errorf("user %s: %w", id, ErrNotFound) } if err != nil { return nil, fmt.Errorf("querying user %s: %w", id, err) } return user, nil } // At the handler level, unwrap to determine response func (h *Handler) GetUser(w http.ResponseWriter, r *http.Request) { user, err := h.service.GetUser(r.Context(), chi.URLParam(r, "id")) if err != nil { switch { case errors.Is(err, domain.ErrNotFound): writeError(w, http.StatusNotFound, "not_found", err.Error()) case errors.Is(err, domain.ErrUnauthorized): writeError(w, http.StatusForbidden, "forbidden", "Access denied") default: slog.Error("unexpected error", "err", err) writeError(w, http.StatusInternalServerError, "internal_error", "An unexpected error occurred") } return } writeJSON(w, http.StatusOK, user) } ``` ## Retry with Exponential Backoff ```typescript interface RetryOptions { maxAttempts?: number baseDelayMs?: number maxDelayMs?: number retryIf?: (error: unknown) => boolean } async function withRetry( fn: () => Promise, options: RetryOptions = {}, ): Promise { const { maxAttempts = 3, baseDelayMs = 500, maxDelayMs = 10_000, retryIf = () => true, } = options let lastError: unknown for (let attempt = 1; attempt <= maxAttempts; attempt++) { try { return await fn() } catch (error) { lastError = error if (attempt === maxAttempts || !retryIf(error)) throw error const jitter = Math.random() * baseDelayMs const delay = Math.min(baseDelayMs * 2 ** (attempt - 1) + jitter, maxDelayMs) await new Promise(resolve => setTimeout(resolve, delay)) } } throw lastError } // Usage: retry transient network errors, not 4xx const data = await withRetry(() => fetch('/api/data').then(r => r.json()), { maxAttempts: 3, retryIf: (error) => !(error instanceof AppError && error.statusCode < 500), }) ``` ## User-Facing Error Messages Map error codes to human-readable messages. Keep technical details out of user-visible text. ```typescript const USER_ERROR_MESSAGES: Record = { NOT_FOUND: 'The requested item could not be found.', UNAUTHORIZED: 'Please sign in to continue.', FORBIDDEN: "You don't have permission to do that.", VALIDATION_ERROR: 'Please check your input and try again.', RATE_LIMITED: 'Too many requests. Please wait a moment and try again.', INTERNAL_ERROR: 'Something went wrong on our end. Please try again later.', } export function getUserMessage(code: string): string { return USER_ERROR_MESSAGES[code] ?? USER_ERROR_MESSAGES.INTERNAL_ERROR } ``` ## Error Handling Checklist Before merging any code that touches error handling: - [ ] Every `catch` block handles, re-throws, or logs — no silent swallowing - [ ] API errors follow the standard envelope `{ error: { code, message } }` - [ ] User-facing messages contain no stack traces or internal details - [ ] Full error context is logged server-side - [ ] Custom error classes extend a base `AppError` with a `code` field - [ ] Async functions surface errors to callers — no fire-and-forget without fallback - [ ] Retry logic only retries retriable errors (not 4xx client errors) - [ ] React components are wrapped in `ErrorBoundary` for rendering errors

相关技能

设计创意

Automation Workflows

设计和实施自动化工作流程,以节省时间和规模化操作作为独家. 用于识别重复任务实现自动化,构建跨工具的工作流程,设置触发器和行动,或优化现有自动化. 包括自动化机会识别,工作流程设计,工具选择(Zapier,Make,n8n),测试,和维护. 触发"自动","自动","工作流程自动…

设计创意

Ui Ux Pro Max

UI/UX设计智能及建筑抛光接口实施指导. 当用户要求UI设计,UX流量,信息架构,视觉风格方向,设计系统/托盘,组件规格,副本/显微镜,可访问性,或生成/critique/refine前端UI(HTML/CSS/JS,React,Next.js,Vue,Svelte,Tailw…

设计创意

Frontend Design

创建美丽现代UI的专家前端设计指南. 在构建起落架页面,仪表板,或任何用户界面时使用.

设计创意

N8n Workflow Automation

设计和输出 n8n 工作流程 JSON 有强力触发器, idempotency, 错误处理, 记录, 重试, 以及 人入"一站"审查队列. 当您需要可审计的自动化时使用.