Community코딩 & 개발github.com

오류 처리 패턴

예외, Result 타입, 오류 전파 및 정상적 성능 저하를 포함한 다양한 언어의 오류 처리 패턴을 마스터하여 탄력적인 애플리케이션을 구축합니다. 오류 처리를 구현하거나, API를 설계하거나, 애플리케이션 신뢰성을 개선할 때 사용하세요.

오류 처리 패턴란 무엇인가요?

이 스킬은 개발자와 AI 에이전트가 예외(Exception), Result 타입, 오류 코드, Option/Maybe 타입 등 다양한 오류 처리 철학을 이해하고 적용할 수 있도록 안내합니다. 복구 가능한 오류(네트워크 타임아웃, 파일 누락 등)와 복구 불가능한 오류(메모리 부족, 스택 오버플로 등)를 구분하고, 각 상황에 적합한 처리 전략을 제시합니다. 특히 '빠르게 실패하기', '컨텍스트 보존', '의미 있는 메시지 제공'과 같은 모범 사례를 코드 예제와 함께 상세히 설명하며, 과도한 예외 포착, 빈 catch 블록, 비동기 오류 무시와 같은 일반적인 함정을 피하는 방법을 알려줍니다. Python, JavaScript, Go, Rust 등 주요 언어에서의 구현 예제를 포함하며, 재시도 및 서킷 브레이커 패턴, 분산 시스템의 오류 허용 한계 등 실무에 바로 적용 가능한 고급 패턴도 다룹니다. 이 스킬을 통해 더 신뢰할 수 있는 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에게 물어보기

이 에이전트 스킬이 미리 로드된 새 채팅을 엽니다.

문서

오류 처리 패턴은(는) 무엇을 하나요?

장애를 우아하게 처리하고 뛰어난 디버깅 경험을 제공하는 강력한 오류 처리 전략으로 탄력적인 애플리케이션을 구축합니다.

이 스킬을 사용해야 할 때

  • 새 기능의 오류 처리 구현
  • 오류에 탄력적인 API 설계
  • 프로덕션 문제 디버깅
  • 애플리케이션 신뢰성 개선
  • 사용자 및 개발자를 위한 더 나은 오류 메시지 생성
  • 재시도 및 서킷 브레이커 패턴 구현
  • 비동기/동시성 오류 처리
  • 내결함성 분산 시스템 구축

핵심 개념

1. 오류 처리 철학

예외 vs Result 타입:

  • 예외: 전통적인 try-catch, 제어 흐름을 방해함
  • Result 타입: 명시적인 성공/실패, 함수형 접근법
  • 오류 코드: C 스타일, 규율 필요
  • Option/Maybe 타입: 널이 가능한 값용

각각을 사용해야 하는 경우:

  • 예외: 예상치 못한 오류, 예외적인 상황
  • Result 타입: 예상된 오류, 유효성 검사 실패
  • 패닉/충돌: 복구 불가능한 오류, 프로그래밍 버그

2. 오류 분류

복구 가능한 오류:

  • 네트워크 타임아웃
  • 파일 누락
  • 잘못된 사용자 입력
  • API 속도 제한

복구 불가능한 오류:

  • 메모리 부족
  • 스택 오버플로
  • 프로그래밍 버그 (null 포인터 등)

상세 패턴 및 실전 예제

상세 패턴 문서는 references/details.md에 있습니다. 위 탐색 계층이 충분하지 않을 경우 해당 파일을 읽으세요.

모범 사례

  1. 빠르게 실패하라: 입력을 조기에 검증하고, 빠르게 실패하세요.
  2. 컨텍스트를 보존하라: 스택 트레이스, 메타데이터, 타임스탬프를 포함하세요.
  3. 의미 있는 메시지: 무슨 일이 일어났는지와 어떻게 해결할 수 있는지 설명하세요.
  4. 적절히 로깅하라: 오류 = 로그, 예상된 실패 = 로그를 스팸으로 채우지 마세요.
  5. 적절한 수준에서 처리하라: 의미 있게 처리할 수 있는 곳에서 잡으세요.
  6. 리소스를 정리하라: try-finally, 컨텍스트 관리자, defer를 사용하세요.
  7. 오류를 삼키지 마라: 로그를 남기거나 다시 던지세요, 조용히 무시하지 마세요.
  8. 타입 안전한 오류: 가능하면 타입이 있는 오류를 사용하세요.
# 좋은 오류 처리 예제
def process_order(order_id: str) -> Order:
    """포괄적인 오류 처리를 사용하여 주문을 처리합니다."""
    try:
        # 입력 검증
        if not order_id:
            raise ValidationError("Order ID is required")

        # 주문 조회
        order = db.get_order(order_id)
        if not order:
            raise NotFoundError("Order", order_id)

        # 결제 처리
        try:
            payment_result = payment_service.charge(order.total)
        except PaymentServiceError as e:
            # 외부 서비스 오류 로깅 및 래핑
            logger.error(f"Payment failed for order {order_id}: {e}")
            raise ExternalServiceError(
                f"Payment processing failed",
                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"Unexpected error processing order {order_id}")
        raise ApplicationError(
            "Order processing failed",
            code="INTERNAL_ERROR"
        ) from e

일반적인 함정

  • 너무 광범위하게 잡기: except Exception은 버그를 숨깁니다.
  • 빈 catch 블록: 오류를 조용히 삼킵니다.
  • 로깅 후 다시 던지기: 중복 로그 항목을 만듭니다.
  • 정리하지 않기: 파일, 연결을 닫는 것을 잊습니다.
  • 나쁜 오류 메시지: "Error occurred"는 도움이 되지 않습니다.
  • 오류 코드 반환: 예외 또는 Result 타입을 사용하세요.
  • 비동기 오류 무시: 처리되지 않은 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.

관련 스킬