Community程式設計與開發github.com

mianhtsys/landingMod3

精通跨語言的錯誤處理模式,包括例外、結果類型、錯誤傳播與優雅降級,打造韌性十足的應用程式。適用於實作錯誤處理、設計 API 或提升應用程式可靠性。

landingMod3 是什麼?

這個技能提供了一個全面的錯誤處理模式庫,涵蓋例外、結果類型、錯誤傳播與優雅降級等核心概念,幫助開發者建立堅固且可偵錯的應用程式。它詳細說明了何時該使用例外 vs 結果類型,並區分可恢復與不可恢復的錯誤類型,讓開發者能根據情境選擇最合適的策略。技能中包含具體的程式碼範例(如 Python 的順序處理),展示如何結合輸入驗證、日誌記錄、錯誤包裝與資源清理,並且強調「快速失敗」、「保留脈絡」與「有意義的錯誤訊息」等最佳實務。此技能適用於任何使用例外或結果類型的主流語言與平台(如 Python、JavaScript、Rust、Go 等),特別是在設計錯誤韌性 API、處理非同步/並行錯誤、以及實作重試與斷路器模式時極為有用。

相容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/mianhtsys/landingMod3/tree/HEAD/MODULO_3_DESARROLLO_AL_LADO_DEL_CLIENTE_Y_SERVIDOR_WEB/architecture-skills-framework/.agents/skills/error-handling-patterns

Installed? Explore more 程式設計與開發 skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

錯誤處理模式

利用強固的錯誤處理策略建立韌性應用程式,優雅地處理失敗,並提供絕佳的除錯體驗。

何時使用此技能

  • 在新功能中實作錯誤處理
  • 設計具錯誤韌性的 API
  • 除錯生產環境問題
  • 提升應用程式可靠性
  • 為使用者和開發者創造更好的錯誤訊息
  • 實作重試與斷路器模式
  • 處理非同步/並行錯誤
  • 建立容錯的分散式系統

核心概念

1. 錯誤處理哲學

例外 vs 結果類型:

  • 例外:傳統的 try-catch,打斷控制流程
  • 結果類型:明確的成功/失敗,函數式方法
  • 錯誤碼:C 語言風格,需要紀律
  • Option/Maybe 類型:用於可為 null 的值

各方法的使用時機:

  • 例外:非預期錯誤、例外狀況
  • 結果類型:預期錯誤、驗證失敗
  • 恐慌/崩潰:不可恢復的錯誤、程式錯誤

2. 錯誤分類

可恢復錯誤:

  • 網路超時
  • 找不到檔案
  • 使用者輸入無效
  • API 速率限制

不可恢復錯誤:

  • 記憶體不足
  • 堆疊溢位
  • 程式錯誤(如空指標)

詳細模式與實際範例

詳細的模式文件存放於 references/details.md。當上述導覽層級不足時,請閱讀該檔案。

最佳實務

  1. 快速失敗:及早驗證輸入,快速失敗
  2. 保留脈絡:包含堆疊追蹤、中繼資料、時間戳記
  3. 有意義的訊息:說明發生什麼事以及如何修正
  4. 適當記錄:錯誤=記錄,預期失敗=不要干擾日誌
  5. 在正確層級處理:在有辦法處理的地方捕捉
  6. 清理資源:使用 try-finally、context manager、defer
  7. 不要吞掉錯誤:記錄或重新拋出,不要默默忽略
  8. 型別安全錯誤:盡可能使用型別化錯誤
# 良好的錯誤處理範例
def process_order(order_id: str) -> Order:
    """處理訂單,包含全面的錯誤處理。"""
    try:
        # 驗證輸入
        if not order_id:
            raise ValidationError("訂單 ID 為必填")

        # 取得訂單
        order = db.get_order(order_id)
        if not order:
            raise NotFoundError("訂單", order_id)

        # 處理付款
        try:
            payment_result = payment_service.charge(order.total)
        except PaymentServiceError as e:
            # 記錄並包裝外部服務錯誤
            logger.error(f"訂單 {order_id} 付款失敗:{e}")
            raise ExternalServiceError(
                f"付款處理失敗",
                service="payment_service",
                details={"order_id": order_id, "amount": order.total}
            ) from e

        # 更新訂單
        order.status = "completed"
        order.payment_id = payment_result.id
        db.save(order)

        return order

    except ApplicationError:
        # 重新拋出已知的應用程式錯誤
        raise
    except Exception as e:
        # 記錄非預期錯誤
        logger.exception(f"處理訂單 {order_id} 時發生非預期錯誤")
        raise ApplicationError(
            "訂單處理失敗",
            code="INTERNAL_ERROR"
        ) from e

常見陷阱

  • 捕捉範圍過大:except Exception 會隱藏錯誤
  • 空的 catch 區塊:默默吞掉錯誤
  • 記錄後又重新拋出:產生重複的日誌項目
  • 未清理資源:忘記關閉檔案、連線
  • 糟糕的錯誤訊息:「發生錯誤」沒有幫助
  • 回傳錯誤碼:應使用例外或結果類型
  • 忽略非同步錯誤:未處理的 Promise 拒絕

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

mianhtsys/landingMod3

Implement WCAG 2.2 compliant interfaces with mobile accessibility, inclusive design patterns, and assistive technology support. Use when auditing accessibility, implementing ARIA patterns, building for screen readers, or ensuring inclusive user experiences.

mianhtsys/landingMod3

Master REST and GraphQL API design principles to build intuitive, scalable, and maintainable APIs that delight developers. Use when designing new APIs, reviewing API specifications, or establishing API design standards.

mianhtsys/landingMod3

Diseña y compara alternativas arquitectónicas trazables a RF/RNF sin implementar código.

mianhtsys/landingMod3

Implement proven backend architecture patterns including Clean Architecture, Hexagonal Architecture, and Domain-Driven Design. Use this skill when designing clean architecture for a new microservice, when refactoring a monolith to use bounded contexts, when implementing hexagonal or onion architecture patterns, or when debugging dependency cycles between application layers.

mianhtsys/landingMod3

Revisión adversarial de la arquitectura contra RF/RNF, detectando contradicciones, cobertura faltante y complejidad innecesaria.

mianhtsys/landingMod3

Master authentication and authorization patterns including JWT, OAuth2, session management, and RBAC to build secure, scalable access control systems. Use when implementing auth systems, securing APIs, or debugging security issues.

mianhtsys/landingMod3

>- Generate grounded-and-verified, engine-agnostic database documentation that reaches 100% parity with the real schema. Introspects the LIVE database as ground truth and cross-validates it against ORM models, migrations, generated types, seeds, and application queries, then proves completeness by diffing the docs back against the database. Produces ER diagrams (mermaid), per-table data dictionaries, and a machine-readable schema.json. Works with PostgreSQL, MySQL, SQL Server, and SQLite across any ORM (Prisma, TypeORM, Drizzle, Sequelize, Knex, Django, Rails) or raw SQL. Use when asked to document a database, produce an ERD or data dictionary, write db/schema docs, audit schema drift, or refresh existing DB docs.

mianhtsys/landingMod3

Compara estrategias de persistencia y motores de datos según consistencia, concurrencia, volumen, recuperación y operación.

mianhtsys/landingMod3

Design robust, scalable database schemas for SQL and NoSQL databases. Provides normalization guidelines, indexing strategies, migration patterns, constraint design, and performance optimization. Ensures data integrity, query performance, and maintainable data models.

mianhtsys/landingMod3

Consolida análisis especializados en una recomendación arquitectónica, matriz de decisión, ADR y plan de validación.

mianhtsys/landingMod3

Build and maintain web frontends — component architecture, state management, API integration, responsive layout, client-side performance, and frontend testing patterns. Framework agnostic, focused on web frontend implementation. Do not use for backend service implementation, data engineering, or platform infrastructure work.

mianhtsys/landingMod3

Evalúa despliegue, contenedores, escalado, alta disponibilidad, observabilidad, backup, recuperación y CI/CD de forma proporcional.

mianhtsys/landingMod3

Execute read-only SQL queries against multiple Microsoft SQL Server databases. Use when: (1) querying MSSQL/SQL Server databases, (2) exploring database schemas/tables, (3) running SELECT queries for data analysis, (4) checking database contents. Supports multiple database connections with descriptions for intelligent auto-selection. Blocks all write operations (INSERT, UPDATE, DELETE, DROP, etc.) for safety.

mianhtsys/landingMod3

Generate and maintain OpenAPI 3.1 specifications from code, design-first specs, and validation patterns. Use when creating API documentation, generating SDKs, or ensuring API contract compliance.

mianhtsys/landingMod3

PHP 8.0+ development — XAMPP, RESTful APIs, PDO/MySQL/MariaDB, and authentication. Use when building PHP backends, creating API endpoints, configuring XAMPP, or integrating PHP with databases.

mianhtsys/landingMod3

Use this skill when designing or reviewing a PostgreSQL-specific schema. Covers best-practices, data types, indexing, constraints, performance patterns, and advanced features

mianhtsys/landingMod3

Analiza requisitos funcionales y no funcionales, reglas, restricciones, capacidad y ambigüedades antes de seleccionar tecnologías.

mianhtsys/landingMod3

Implement modern responsive layouts using container queries, fluid typography, CSS Grid, and mobile-first breakpoint strategies. Use when building adaptive interfaces, implementing fluid layouts, or creating component-level responsive behavior.

mianhtsys/landingMod3

>- Use when designing or implementing software securely: define security requirements, threat-model a feature, choose secure defaults, design authentication and authorization, handle untrusted data and secrets, evaluate dependencies, design multi-tenant trust boundaries, or review security-sensitive changes. Use for prevention during requirements, design, implementation, and review; not for post-build security assessments or scanning an existing codebase.

mianhtsys/landingMod3

Revisa seguridad arquitectónica, identidad, autorización, secretos, APIs, auditoría, fraude y resiliencia antes de implementar.

相關技能