[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7AK70SKBAZ1YMP4WZ7RMBKT":3,"skill-same:01M7AK70SKBAZ1YMP4WZ7RMBKT":48},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":25,"commitSha":26,"skillDirectory":27,"forksCount":28,"repositoryHtmlUrl":29,"repositoryHomepageUrl":6,"ownerHtmlUrl":30,"ownerBlogUrl":31,"ownerDescription":32,"updatedAt":33,"install":34,"resources":47},"01M7AK70SKBAZ1YMP4WZ7RMBKT","error-handling",null,"TypeScript、Python、Goにわたる堅牢なエラー処理のパターン。型付きエラー、エラー境界、リトライ、サーキットブレーカー、ユーザー向けエラーメッセージをカバーします。","Cyrilthetecchieee\u002Fcyril-code-","Cyrilthetecchieee","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F219787998?v=4","01M7AF0MMMKRAA0H61XMJPV92H","Julian Cyril D ","01M7AF0MQ10AVG6QJQ1C2BC0F5",2,"MIT","https:\u002F\u002Fgithub.com\u002FCyrilthetecchieee\u002Fcyril-code-\u002Fblob\u002Fmain\u002Fsrc\u002Fcyril_code\u002Fassets\u002F.skills_repo\u002Fdocs\u002Fja-JP\u002Fskills\u002Ferror-handling\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: error-handling\ndescription: TypeScript、Python、Goにわたる堅牢なエラー処理のパターン。型付きエラー、エラー境界、リトライ、サーキットブレーカー、ユーザー向けエラーメッセージをカバーします。\norigin: ECC\n---\n\n# エラー処理パターン\n\n本番アプリケーション向けの一貫した堅牢なエラー処理パターン。\n\n## アクティベートするタイミング\n\n- 新しいモジュールやサービスのエラー型や例外階層を設計する場合\n- 信頼性の低い外部依存関係に対してリトライロジックやサーキットブレーカーを追加する場合\n- APIエンドポイントでエラー処理の欠落をレビューする場合\n- ユーザー向けエラーメッセージとフィードバックを実装する場合\n- カスケード障害やサイレントなエラー飲み込みをデバッグする場合\n\n## コア原則\n\n1. **早く大きく失敗する** — エラーが発生した境界で表面化させる。埋め込まない\n2. **文字列メッセージより型付きエラー** — エラーは構造を持つファーストクラスの値\n3. **ユーザーメッセージ ≠ 開発者メッセージ** — ユーザーには親しみやすいテキストを表示し、詳細なコンテキストはサーバー側でログに記録する\n4. **エラーをサイレントに飲み込まない** — すべての`catch`ブロックは処理、再スロー、またはログのいずれかを行う必要がある\n5. **エラーはAPIコントラクトの一部** — クライアントが受け取る可能性があるすべてのエラーコードをドキュメント化する\n\n## TypeScript \u002F JavaScript\n\n### 型付きエラークラス\n\n```typescript\n\u002F\u002F ドメインのエラー階層を定義する\nexport class AppError extends Error {\n  constructor(\n    message: string,\n    public readonly code: string,\n    public readonly statusCode: number = 500,\n    public readonly details?: unknown,\n  ) {\n    super(message)\n    this.name = this.constructor.name\n    \u002F\u002F トランスパイルされたES5 JavaScriptでプロトタイプチェーンを正しく維持する。\n    \u002F\u002F 組み込みのErrorクラスを拡張する際に`instanceof`チェック\n    \u002F\u002F （例: `error instanceof NotFoundError`）が正しく動作するために必要。\n    Object.setPrototypeOf(this, new.target.prototype)\n  }\n}\n\nexport class NotFoundError extends AppError {\n  constructor(resource: string, id: string) {\n    super(`${resource} not found: ${id}`, 'NOT_FOUND', 404)\n  }\n}\n\nexport class ValidationError extends AppError {\n  constructor(message: string, details: { field: string; message: string }[]) {\n    super(message, 'VALIDATION_ERROR', 422, details)\n  }\n}\n\nexport class UnauthorizedError extends AppError {\n  constructor(reason = 'Authentication required') {\n    super(reason, 'UNAUTHORIZED', 401)\n  }\n}\n\nexport class RateLimitError extends AppError {\n  constructor(public readonly retryAfterMs: number) {\n    super('Rate limit exceeded', 'RATE_LIMITED', 429)\n  }\n}\n```\n\n### Resultパターン（スロー不使用スタイル）\n\n失敗が想定され一般的な操作（パース、外部呼び出し）向け:\n\n```typescript\ntype Result\u003CT, E = AppError> =\n  | { ok: true; value: T }\n  | { ok: false; error: E }\n\nfunction ok\u003CT>(value: T): Result\u003CT> {\n  return { ok: true, value }\n}\n\nfunction err\u003CE>(error: E): Result\u003Cnever, E> {\n  return { ok: false, error }\n}\n\n\u002F\u002F 使用例\nasync function fetchUser(id: string): Promise\u003CResult\u003CUser>> {\n  try {\n    const user = await db.users.findUnique({ where: { id } })\n    if (!user) return err(new NotFoundError('User', id))\n    return ok(user)\n  } catch (e) {\n    return err(new AppError('Database error', 'DB_ERROR'))\n  }\n}\n\nconst result = await fetchUser('abc-123')\nif (!result.ok) {\n  \u002F\u002F TypeScriptはここでresult.errorを認識する\n  logger.error('Failed to fetch user', { error: result.error })\n  return\n}\n\u002F\u002F TypeScriptはここでresult.valueを認識する\nconsole.log(result.value.email)\n```\n\n### APIエラーハンドラー（Next.js \u002F Express）\n\n```typescript\nimport { NextRequest, NextResponse } from 'next\u002Fserver'\n\nfunction handleApiError(error: unknown): NextResponse {\n  \u002F\u002F 既知のアプリケーションエラー\n  if (error instanceof AppError) {\n    return NextResponse.json(\n      {\n        error: {\n          code: error.code,\n          message: error.message,\n          ...(error.details ? { details: error.details } : {}),\n        },\n      },\n      { status: error.statusCode },\n    )\n  }\n\n  \u002F\u002F Zodバリデーションエラー\n  if (error instanceof z.ZodError) {\n    return NextResponse.json(\n      {\n        error: {\n          code: 'VALIDATION_ERROR',\n          message: 'Request validation failed',\n          details: error.issues.map(i => ({\n            field: i.path.join('.'),\n            message: i.message,\n          })),\n        },\n      },\n      { status: 422 },\n    )\n  }\n\n  \u002F\u002F 予期しないエラー — 詳細をログに記録し、汎用メッセージを返す\n  console.error('Unexpected error:', error)\n  return NextResponse.json(\n    { error: { code: 'INTERNAL_ERROR', message: 'An unexpected error occurred' } },\n    { status: 500 },\n  )\n}\n\nexport async function POST(req: NextRequest) {\n  try {\n    \u002F\u002F ... ハンドラーロジック\n  } catch (error) {\n    return handleApiError(error)\n  }\n}\n```\n\n### ReactエラーバウンダリーII\n\n```typescript\nimport { Component, ErrorInfo, ReactNode } from 'react'\n\ninterface Props {\n  fallback: ReactNode\n  onError?: (error: Error, info: ErrorInfo) => void\n  children: ReactNode\n}\n\ninterface State {\n  hasError: boolean\n  error: Error | null\n}\n\nexport class ErrorBoundary extends Component\u003CProps, State> {\n  state: State = { hasError: false, error: null }\n\n  static getDerivedStateFromError(error: Error): State {\n    return { hasError: true, error }\n  }\n\n  componentDidCatch(error: Error, info: ErrorInfo) {\n    this.props.onError?.(error, info)\n    console.error('Unhandled React error:', error, info)\n  }\n\n  render() {\n    if (this.state.hasError) return this.props.fallback\n    return this.props.children\n  }\n}\n\n\u002F\u002F 使用例\n\u003CErrorBoundary fallback={\u003Cp>Something went wrong. Please refresh.\u003C\u002Fp>}>\n  \u003CMyComponent \u002F>\n\u003C\u002FErrorBoundary>\n```\n\n## Python\n\n### カスタム例外階層\n\n```python\nclass AppError(Exception):\n    \"\"\"基底アプリケーションエラー。\"\"\"\n    def __init__(self, message: str, code: str, status_code: int = 500):\n        super().__init__(message)\n        self.code = code\n        self.status_code = status_code\n\nclass NotFoundError(AppError):\n    def __init__(self, resource: str, id: str):\n        super().__init__(f\"{resource} not found: {id}\", \"NOT_FOUND\", 404)\n\nclass ValidationError(AppError):\n    def __init__(self, message: str, details: list[dict] | None = None):\n        super().__init__(message, \"VALIDATION_ERROR\", 422)\n        self.details = details or []\n```\n\n### FastAPIグローバル例外ハンドラー\n\n```python\nfrom fastapi import FastAPI, Request\nfrom fastapi.responses import JSONResponse\n\napp = FastAPI()\n\n@app.exception_handler(AppError)\nasync def app_error_handler(request: Request, exc: AppError) -> JSONResponse:\n    return JSONResponse(\n        status_code=exc.status_code,\n        content={\"error\": {\"code\": exc.code, \"message\": str(exc)}},\n    )\n\n@app.exception_handler(Exception)\nasync def generic_error_handler(request: Request, exc: Exception) -> JSONResponse:\n    # 詳細をログに記録し、汎用メッセージを返す\n    logger.exception(\"Unexpected error\", exc_info=exc)\n    return JSONResponse(\n        status_code=500,\n        content={\"error\": {\"code\": \"INTERNAL_ERROR\", \"message\": \"An unexpected error occurred\"}},\n    )\n```\n\n## Go\n\n### センチネルエラーとエラーラッピング\n\n```go\npackage domain\n\nimport \"errors\"\n\n\u002F\u002F 型チェック用センチネルエラー\nvar (\n    ErrNotFound    = errors.New(\"not found\")\n    ErrUnauthorized = errors.New(\"unauthorized\")\n    ErrConflict     = errors.New(\"conflict\")\n)\n\n\u002F\u002F コンテキスト付きでエラーをラップする — 元のエラーを失わない\nfunc (r *UserRepository) FindByID(ctx context.Context, id string) (*User, error) {\n    user, err := r.db.QueryRow(ctx, \"SELECT * FROM users WHERE id = $1\", id)\n    if errors.Is(err, sql.ErrNoRows) {\n        return nil, fmt.Errorf(\"user %s: %w\", id, ErrNotFound)\n    }\n    if err != nil {\n        return nil, fmt.Errorf(\"querying user %s: %w\", id, err)\n    }\n    return user, nil\n}\n\n\u002F\u002F ハンドラーレベルでアンラップしてレスポンスを決定する\nfunc (h *Handler) GetUser(w http.ResponseWriter, r *http.Request) {\n    user, err := h.service.GetUser(r.Context(), chi.URLParam(r, \"id\"))\n    if err != nil {\n        switch {\n        case errors.Is(err, domain.ErrNotFound):\n            writeError(w, http.StatusNotFound, \"not_found\", err.Error())\n        case errors.Is(err, domain.ErrUnauthorized):\n            writeError(w, http.StatusForbidden, \"forbidden\", \"Access denied\")\n        default:\n            slog.Error(\"unexpected error\", \"err\", err)\n            writeError(w, http.StatusInternalServerError, \"internal_error\", \"An unexpected error occurred\")\n        }\n        return\n    }\n    writeJSON(w, http.StatusOK, user)\n}\n```\n\n## 指数バックオフ付きリトライ\n\n```typescript\ninterface RetryOptions {\n  maxAttempts?: number\n  baseDelayMs?: number\n  maxDelayMs?: number\n  retryIf?: (error: unknown) => boolean\n}\n\nasync function withRetry\u003CT>(\n  fn: () => Promise\u003CT>,\n  options: RetryOptions = {},\n): Promise\u003CT> {\n  const {\n    maxAttempts = 3,\n    baseDelayMs = 500,\n    maxDelayMs = 10_000,\n    retryIf = () => true,\n  } = options\n\n  let lastError: unknown\n\n  for (let attempt = 1; attempt \u003C= maxAttempts; attempt++) {\n    try {\n      return await fn()\n    } catch (error) {\n      lastError = error\n      if (attempt === maxAttempts || !retryIf(error)) throw error\n\n      const jitter = Math.random() * baseDelayMs\n      const delay = Math.min(baseDelayMs * 2 ** (attempt - 1) + jitter, maxDelayMs)\n      await new Promise(resolve => setTimeout(resolve, delay))\n    }\n  }\n\n  throw lastError\n}\n\n\u002F\u002F 使用例: 一時的なネットワークエラーはリトライ、4xxはリトライしない\nconst data = await withRetry(() => fetch('\u002Fapi\u002Fdata').then(r => r.json()), {\n  maxAttempts: 3,\n  retryIf: (error) => !(error instanceof AppError && error.statusCode \u003C 500),\n})\n```\n\n## ユーザー向けエラーメッセージ\n\nエラーコードを人間が読めるメッセージにマッピングする。技術的な詳細はユーザーに見えるテキストに含めない。\n\n```typescript\nconst USER_ERROR_MESSAGES: Record\u003Cstring, string> = {\n  NOT_FOUND: 'The requested item could not be found.',\n  UNAUTHORIZED: 'Please sign in to continue.',\n  FORBIDDEN: \"You don't have permission to do that.\",\n  VALIDATION_ERROR: 'Please check your input and try again.',\n  RATE_LIMITED: 'Too many requests. Please wait a moment and try again.',\n  INTERNAL_ERROR: 'Something went wrong on our end. Please try again later.',\n}\n\nexport function getUserMessage(code: string): string {\n  return USER_ERROR_MESSAGES[code] ?? USER_ERROR_MESSAGES.INTERNAL_ERROR\n}\n```\n\n## エラー処理チェックリスト\n\nエラー処理に触れるコードをマージする前に:\n\n- [ ] すべての`catch`ブロックが処理、再スロー、またはログを行っている — サイレントな飲み込みなし\n- [ ] APIエラーが標準エンベロープ`{ error: { code, message } }`に従っている\n- [ ] ユーザー向けメッセージにスタックトレースや内部詳細が含まれていない\n- [ ] サーバー側で完全なエラーコンテキストがログに記録されている\n- [ ] カスタムエラークラスが`code`フィールドを持つ基底`AppError`を継承している\n- [ ] 非同期関数がエラーを呼び出し元に伝播している — フォールバックなしの fire-and-forget なし\n- [ ] リトライロジックがリトライ可能なエラーのみをリトライしている（4xxクライアントエラーはリトライしない）\n- [ ] Reactコンポーネントがレンダリングエラーのために`ErrorBoundary`でラップされている\n","# エラー処理パターン\n\n本番アプリケーション向けの一貫した堅牢なエラー処理パターン。\n\n## アクティベートするタイミング\n\n- 新しいモジュールやサービスのエラー型や例外階層を設計する場合\n- 信頼性の低い外部依存関係に対してリトライロジックやサーキットブレーカーを追加する場合\n- APIエンドポイントでエラー処理の欠落をレビューする場合\n- ユーザー向けエラーメッセージとフィードバックを実装する場合\n- カスケード障害やサイレントなエラー飲み込みをデバッグする場合\n\n## コア原則\n\n1. **早く大きく失敗する** — エラーが発生した境界で表面化させる。埋め込まない\n2. **文字列メッセージより型付きエラー** — エラーは構造を持つファーストクラスの値\n3. **ユーザーメッセージ ≠ 開発者メッセージ** — ユーザーには親しみやすいテキストを表示し、詳細なコンテキストはサーバー側でログに記録する\n4. **エラーをサイレントに飲み込まない** — すべての`catch`ブロックは処理、再スロー、またはログのいずれかを行う必要がある\n5. **エラーはAPIコントラクトの一部** — クライアントが受け取る可能性があるすべてのエラーコードをドキュメント化する\n\n## TypeScript \u002F JavaScript\n\n### 型付きエラークラス\n\n```typescript\n\u002F\u002F ドメインのエラー階層を定義する\nexport class AppError extends Error {\n  constructor(\n    message: string,\n    public readonly code: string,\n    public readonly statusCode: number = 500,\n    public readonly details?: unknown,\n  ) {\n    super(message)\n    this.name = this.constructor.name\n    \u002F\u002F トランスパイルされたES5 JavaScriptでプロトタイプチェーンを正しく維持する。\n    \u002F\u002F 組み込みのErrorクラスを拡張する際に`instanceof`チェック\n    \u002F\u002F （例: `error instanceof NotFoundError`）が正しく動作するために必要。\n    Object.setPrototypeOf(this, new.target.prototype)\n  }\n}\n\nexport class NotFoundError extends AppError {\n  constructor(resource: string, id: string) {\n    super(`${resource} not found: ${id}`, 'NOT_FOUND', 404)\n  }\n}\n\nexport class ValidationError extends AppError {\n  constructor(message: string, details: { field: string; message: string }[]) {\n    super(message, 'VALIDATION_ERROR', 422, details)\n  }\n}\n\nexport class UnauthorizedError extends AppError {\n  constructor(reason = 'Authentication required') {\n    super(reason, 'UNAUTHORIZED', 401)\n  }\n}\n\nexport class RateLimitError extends AppError {\n  constructor(public readonly retryAfterMs: number) {\n    super('Rate limit exceeded', 'RATE_LIMITED', 429)\n  }\n}\n```\n\n### Resultパターン（スロー不使用スタイル）\n\n失敗が想定され一般的な操作（パース、外部呼び出し）向け:\n\n```typescript\ntype Result\u003CT, E = AppError> =\n  | { ok: true; value: T }\n  | { ok: false; error: E }\n\nfunction ok\u003CT>(value: T): Result\u003CT> {\n  return { ok: true, value }\n}\n\nfunction err\u003CE>(error: E): Result\u003Cnever, E> {\n  return { ok: false, error }\n}\n\n\u002F\u002F 使用例\nasync function fetchUser(id: string): Promise\u003CResult\u003CUser>> {\n  try {\n    const user = await db.users.findUnique({ where: { id } })\n    if (!user) return err(new NotFoundError('User', id))\n    return ok(user)\n  } catch (e) {\n    return err(new AppError('Database error', 'DB_ERROR'))\n  }\n}\n\nconst result = await fetchUser('abc-123')\nif (!result.ok) {\n  \u002F\u002F TypeScriptはここでresult.errorを認識する\n  logger.error('Failed to fetch user', { error: result.error })\n  return\n}\n\u002F\u002F TypeScriptはここでresult.valueを認識する\nconsole.log(result.value.email)\n```\n\n### APIエラーハンドラー（Next.js \u002F Express）\n\n```typescript\nimport { NextRequest, NextResponse } from 'next\u002Fserver'\n\nfunction handleApiError(error: unknown): NextResponse {\n  \u002F\u002F 既知のアプリケーションエラー\n  if (error instanceof AppError) {\n    return NextResponse.json(\n      {\n        error: {\n          code: error.code,\n          message: error.message,\n          ...(error.details ? { details: error.details } : {}),\n        },\n      },\n      { status: error.statusCode },\n    )\n  }\n\n  \u002F\u002F Zodバリデーションエラー\n  if (error instanceof z.ZodError) {\n    return NextResponse.json(\n      {\n        error: {\n          code: 'VALIDATION_ERROR',\n          message: 'Request validation failed',\n          details: error.issues.map(i => ({\n            field: i.path.join('.'),\n            message: i.message,\n          })),\n        },\n      },\n      { status: 422 },\n    )\n  }\n\n  \u002F\u002F 予期しないエラー — 詳細をログに記録し、汎用メッセージを返す\n  console.error('Unexpected error:', error)\n  return NextResponse.json(\n    { error: { code: 'INTERNAL_ERROR', message: 'An unexpected error occurred' } },\n    { status: 500 },\n  )\n}\n\nexport async function POST(req: NextRequest) {\n  try {\n    \u002F\u002F ... ハンドラーロジック\n  } catch (error) {\n    return handleApiError(error)\n  }\n}\n```\n\n### ReactエラーバウンダリーII\n\n```typescript\nimport { Component, ErrorInfo, ReactNode } from 'react'\n\ninterface Props {\n  fallback: ReactNode\n  onError?: (error: Error, info: ErrorInfo) => void\n  children: ReactNode\n}\n\ninterface State {\n  hasError: boolean\n  error: Error | null\n}\n\nexport class ErrorBoundary extends Component\u003CProps, State> {\n  state: State = { hasError: false, error: null }\n\n  static getDerivedStateFromError(error: Error): State {\n    return { hasError: true, error }\n  }\n\n  componentDidCatch(error: Error, info: ErrorInfo) {\n    this.props.onError?.(error, info)\n    console.error('Unhandled React error:', error, info)\n  }\n\n  render() {\n    if (this.state.hasError) return this.props.fallback\n    return this.props.children\n  }\n}\n\n\u002F\u002F 使用例\n\u003CErrorBoundary fallback={\u003Cp>Something went wrong. Please refresh.\u003C\u002Fp>}>\n  \u003CMyComponent \u002F>\n\u003C\u002FErrorBoundary>\n```\n\n## Python\n\n### カスタム例外階層\n\n```python\nclass AppError(Exception):\n    \"\"\"基底アプリケーションエラー。\"\"\"\n    def __init__(self, message: str, code: str, status_code: int = 500):\n        super().__init__(message)\n        self.code = code\n        self.status_code = status_code\n\nclass NotFoundError(AppError):\n    def __init__(self, resource: str, id: str):\n        super().__init__(f\"{resource} not found: {id}\", \"NOT_FOUND\", 404)\n\nclass ValidationError(AppError):\n    def __init__(self, message: str, details: list[dict] | None = None):\n        super().__init__(message, \"VALIDATION_ERROR\", 422)\n        self.details = details or []\n```\n\n### FastAPIグローバル例外ハンドラー\n\n```python\nfrom fastapi import FastAPI, Request\nfrom fastapi.responses import JSONResponse\n\napp = FastAPI()\n\n@app.exception_handler(AppError)\nasync def app_error_handler(request: Request, exc: AppError) -> JSONResponse:\n    return JSONResponse(\n        status_code=exc.status_code,\n        content={\"error\": {\"code\": exc.code, \"message\": str(exc)}},\n    )\n\n@app.exception_handler(Exception)\nasync def generic_error_handler(request: Request, exc: Exception) -> JSONResponse:\n    # 詳細をログに記録し、汎用メッセージを返す\n    logger.exception(\"Unexpected error\", exc_info=exc)\n    return JSONResponse(\n        status_code=500,\n        content={\"error\": {\"code\": \"INTERNAL_ERROR\", \"message\": \"An unexpected error occurred\"}},\n    )\n```\n\n## Go\n\n### センチネルエラーとエラーラッピング\n\n```go\npackage domain\n\nimport \"errors\"\n\n\u002F\u002F 型チェック用センチネルエラー\nvar (\n    ErrNotFound    = errors.New(\"not found\")\n    ErrUnauthorized = errors.New(\"unauthorized\")\n    ErrConflict     = errors.New(\"conflict\")\n)\n\n\u002F\u002F コンテキスト付きでエラーをラップする — 元のエラーを失わない\nfunc (r *UserRepository) FindByID(ctx context.Context, id string) (*User, error) {\n    user, err := r.db.QueryRow(ctx, \"SELECT * FROM users WHERE id = $1\", id)\n    if errors.Is(err, sql.ErrNoRows) {\n        return nil, fmt.Errorf(\"user %s: %w\", id, ErrNotFound)\n    }\n    if err != nil {\n        return nil, fmt.Errorf(\"querying user %s: %w\", id, err)\n    }\n    return user, nil\n}\n\n\u002F\u002F ハンドラーレベルでアンラップしてレスポンスを決定する\nfunc (h *Handler) GetUser(w http.ResponseWriter, r *http.Request) {\n    user, err := h.service.GetUser(r.Context(), chi.URLParam(r, \"id\"))\n    if err != nil {\n        switch {\n        case errors.Is(err, domain.ErrNotFound):\n            writeError(w, http.StatusNotFound, \"not_found\", err.Error())\n        case errors.Is(err, domain.ErrUnauthorized):\n            writeError(w, http.StatusForbidden, \"forbidden\", \"Access denied\")\n        default:\n            slog.Error(\"unexpected error\", \"err\", err)\n            writeError(w, http.StatusInternalServerError, \"internal_error\", \"An unexpected error occurred\")\n        }\n        return\n    }\n    writeJSON(w, http.StatusOK, user)\n}\n```\n\n## 指数バックオフ付きリトライ\n\n```typescript\ninterface RetryOptions {\n  maxAttempts?: number\n  baseDelayMs?: number\n  maxDelayMs?: number\n  retryIf?: (error: unknown) => boolean\n}\n\nasync function withRetry\u003CT>(\n  fn: () => Promise\u003CT>,\n  options: RetryOptions = {},\n): Promise\u003CT> {\n  const {\n    maxAttempts = 3,\n    baseDelayMs = 500,\n    maxDelayMs = 10_000,\n    retryIf = () => true,\n  } = options\n\n  let lastError: unknown\n\n  for (let attempt = 1; attempt \u003C= maxAttempts; attempt++) {\n    try {\n      return await fn()\n    } catch (error) {\n      lastError = error\n      if (attempt === maxAttempts || !retryIf(error)) throw error\n\n      const jitter = Math.random() * baseDelayMs\n      const delay = Math.min(baseDelayMs * 2 ** (attempt - 1) + jitter, maxDelayMs)\n      await new Promise(resolve => setTimeout(resolve, delay))\n    }\n  }\n\n  throw lastError\n}\n\n\u002F\u002F 使用例: 一時的なネットワークエラーはリトライ、4xxはリトライしない\nconst data = await withRetry(() => fetch('\u002Fapi\u002Fdata').then(r => r.json()), {\n  maxAttempts: 3,\n  retryIf: (error) => !(error instanceof AppError && error.statusCode \u003C 500),\n})\n```\n\n## ユーザー向けエラーメッセージ\n\nエラーコードを人間が読めるメッセージにマッピングする。技術的な詳細はユーザーに見えるテキストに含めない。\n\n```typescript\nconst USER_ERROR_MESSAGES: Record\u003Cstring, string> = {\n  NOT_FOUND: 'The requested item could not be found.',\n  UNAUTHORIZED: 'Please sign in to continue.',\n  FORBIDDEN: \"You don't have permission to do that.\",\n  VALIDATION_ERROR: 'Please check your input and try again.',\n  RATE_LIMITED: 'Too many requests. Please wait a moment and try again.',\n  INTERNAL_ERROR: 'Something went wrong on our end. Please try again later.',\n}\n\nexport function getUserMessage(code: string): string {\n  return USER_ERROR_MESSAGES[code] ?? USER_ERROR_MESSAGES.INTERNAL_ERROR\n}\n```\n\n## エラー処理チェックリスト\n\nエラー処理に触れるコードをマージする前に:\n\n- [ ] すべての`catch`ブロックが処理、再スロー、またはログを行っている — サイレントな飲み込みなし\n- [ ] APIエラーが標準エンベロープ`{ error: { code, message } }`に従っている\n- [ ] ユーザー向けメッセージにスタックトレースや内部詳細が含まれていない\n- [ ] サーバー側で完全なエラーコンテキストがログに記録されている\n- [ ] カスタムエラークラスが`code`フィールドを持つ基底`AppError`を継承している\n- [ ] 非同期関数がエラーを呼び出し元に伝播している — フォールバックなしの fire-and-forget なし\n- [ ] リトライロジックがリトライ可能なエラーのみをリトライしている（4xxクライアントエラーはリトライしない）\n- [ ] Reactコンポーネントがレンダリングエラーのために`ErrorBoundary`でラップされている\n",{"name":5,"origin":24,"description":7},"ECC","main","57e7aa6b6e03bce1a7d7862ba9c2ec312f7f19b5","src\u002Fcyril_code\u002Fassets\u002F.skills_repo\u002Fdocs\u002Fja-JP\u002Fskills\u002Ferror-handling",0,"https:\u002F\u002Fgithub.com\u002FCyrilthetecchieee\u002Fcyril-code-","https:\u002F\u002Fgithub.com\u002FCyrilthetecchieee","https:\u002F\u002Fwithcyril.me\u002F","Hi, I’m Julian Cyril D, a Computer Science and Business Systems student at PSNACET.\r\nI’m passionate about full-stack development, UI\u002FUX design, and building sma","2026-11-04 23:28:50",{"source":8,"skillName":5,"commands":35,"prompt":45,"zipAvailable":46},[36,39,42],{"tool":37,"command":38},"npx","npx skills add Cyrilthetecchieee\u002Fcyril-code- --skill error-handling",{"tool":40,"command":41},"bunx","bunx skills add Cyrilthetecchieee\u002Fcyril-code- --skill error-handling",{"tool":43,"command":44},"pnpm","pnpm dlx skills add Cyrilthetecchieee\u002Fcyril-code- --skill error-handling","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FCyrilthetecchieee\u002Fcyril-code-\u002Fblob\u002Fmain\u002Fsrc\u002Fcyril_code\u002Fassets\u002F.skills_repo\u002Fdocs\u002Fja-JP\u002Fskills\u002Ferror-handling\u002FSKILL.md",true,[],[49,58,65,73,80,87],{"skillNo":50,"name":51,"nameZh":6,"description":52,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":53,"licenseFileUrl":54,"sourceHtmlUrl":55,"categories":56,"keywords":57,"publishedAt":19},"01M7AQV6CYX8RMC78420V9WZ62","webapp-testing","Toolkit for interacting with and testing local web applications using Playwright. Supports verifying frontend functionality, debugging UI behavior, capturing browser screenshots, and viewing browser logs.","Apache-2.0","https:\u002F\u002Fgithub.com\u002FCyrilthetecchieee\u002Fcyril-code-\u002Fblob\u002Fmain\u002Fsrc\u002Fcyril_code\u002Fassets\u002F.skills_repo\u002Fwebapp-testing\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002FCyrilthetecchieee\u002Fcyril-code-\u002Fblob\u002Fmain\u002Fsrc\u002Fcyril_code\u002Fassets\u002F.skills_repo\u002Fwebapp-testing\u002FSKILL.md",[],[],{"skillNo":59,"name":60,"nameZh":6,"description":61,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":62,"categories":63,"keywords":64,"publishedAt":19},"01M7AQV2895N3S1MEX6K76G6G2","youtube-downloader","Download YouTube videos with customizable quality and format options. Use this skill when the user asks to download, save, or grab YouTube videos. Supports various quality settings (best, 1080p, 720p, 480p, 360p), multiple formats (mp4, webm, mkv), and audio-only downloads as MP3.","https:\u002F\u002Fgithub.com\u002FCyrilthetecchieee\u002Fcyril-code-\u002Fblob\u002Fmain\u002Fsrc\u002Fcyril_code\u002Fassets\u002F.skills_repo\u002Fvideo-downloader\u002FSKILL.md",[],[],{"skillNo":66,"name":67,"nameZh":6,"description":68,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":53,"licenseFileUrl":69,"sourceHtmlUrl":70,"categories":71,"keywords":72,"publishedAt":19},"01M7AQTRNX62DNKVZ5GXEHRBKB","theme-factory","Toolkit for styling artifacts with a theme. These artifacts can be slides, docs, reportings, HTML landing pages, etc. There are 10 pre-set themes with colors\u002Ffonts that you can apply to any artifact that has been creating, or can generate a new theme on-the-fly.","https:\u002F\u002Fgithub.com\u002FCyrilthetecchieee\u002Fcyril-code-\u002Fblob\u002Fmain\u002Fsrc\u002Fcyril_code\u002Fassets\u002F.skills_repo\u002Ftheme-factory\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002FCyrilthetecchieee\u002Fcyril-code-\u002Fblob\u002Fmain\u002Fsrc\u002Fcyril_code\u002Fassets\u002F.skills_repo\u002Ftheme-factory\u002FSKILL.md",[],[],{"skillNo":74,"name":75,"nameZh":6,"description":76,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":77,"categories":78,"keywords":79,"publishedAt":19},"01M7AQTNNVHAAN9H6DA8T6ZVE0","template-skill","Replace with description of the skill and when Claude should use it.","https:\u002F\u002Fgithub.com\u002FCyrilthetecchieee\u002Fcyril-code-\u002Fblob\u002Fmain\u002Fsrc\u002Fcyril_code\u002Fassets\u002F.skills_repo\u002Ftemplate-skill\u002FSKILL.md",[],[],{"skillNo":81,"name":82,"nameZh":6,"description":83,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":84,"categories":85,"keywords":86,"publishedAt":19},"01M7AQTJ3MQ6AKX152MEX2MYCC","tailored-resume-generator","Analyzes job descriptions and generates tailored resumes that highlight relevant experience, skills, and achievements to maximize interview chances","https:\u002F\u002Fgithub.com\u002FCyrilthetecchieee\u002Fcyril-code-\u002Fblob\u002Fmain\u002Fsrc\u002Fcyril_code\u002Fassets\u002F.skills_repo\u002Ftailored-resume-generator\u002FSKILL.md",[],[],{"skillNo":88,"name":89,"nameZh":6,"description":90,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":53,"licenseFileUrl":91,"sourceHtmlUrl":92,"categories":93,"keywords":94,"publishedAt":19},"01M7AQTD7D5MYET2YWG7HG9WM3","slack-gif-creator","Toolkit for creating animated GIFs optimized for Slack, with validators for size constraints and composable animation primitives. This skill applies when users request animated GIFs or emoji animations for Slack from descriptions like \"make me a GIF for Slack of X doing Y\".","https:\u002F\u002Fgithub.com\u002FCyrilthetecchieee\u002Fcyril-code-\u002Fblob\u002Fmain\u002Fsrc\u002Fcyril_code\u002Fassets\u002F.skills_repo\u002Fslack-gif-creator\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002FCyrilthetecchieee\u002Fcyril-code-\u002Fblob\u002Fmain\u002Fsrc\u002Fcyril_code\u002Fassets\u002F.skills_repo\u002Fslack-gif-creator\u002FSKILL.md",[],[]]