본문으로 건너뛰기
Skillpedia
일반 코딩41k · #6679

error-handling-patterns

하는 일

이 도구는 컴퓨터 프로그램에서 오류를 처리하는 방법을 가르칩니다. 쉽게 '고장' 나지 않고, 무언가 잘못되었을 때 유용한 메시지를 제공하는 더 신뢰할 수 있는 애플리케이션을 만드는 데 도움을 줍니다.

사용하는 경우

  • ✓프로그램의 새 부분을 만들 때.
  • ✓문제가 있어도 웹사이트나 앱이 계속 작동하게 하려는 경우.
  • ✓프로그램에서 발생한 오류를 이해하고 고칠 때.

스킬 링크

https://github.com/wshobson/agents/blob/main/plugins/developer-essentials/skills/error-handling-patterns/SKILL.md

복사해서 AI(Claude, ChatGPT, Cursor)에 붙여넣고 지침을 따르도록 요청하세요.

사용 방법

가장 쉬운 방법입니다. 메시지를 복사해 AI에 붙여넣으세요. AI가 스킬을 읽고 지침을 따릅니다.

바로 붙여넣을 수 있는 메시지

Use this skill to help me: https://github.com/wshobson/agents/blob/main/plugins/developer-essentials/skills/error-handling-patterns/SKILL.md Read the SKILL.md file at that link and follow its instructions for my task.
AI가 이런 스킬을 알아서 찾아 쓰길 원하시나요?무료 Skillpedia MCP를 설치하세요. 한 줄이면 작업마다 스킬 15,000+개 중에서 검색합니다.1분 만에 설치 →

AI에게 요청하는 예시

“데이터가 없을 때 앱이 사용자에게 그것을 분명히 알리게 하려면 어떻게 해야 하나요?”

매주 새 스킬 5개. 읽는 데 1분.

작동 방식

오류를 다루는 여러 방법을 설명합니다. 정상 흐름을 방해하는 '예외'(오류 경고)와, 성공 또는 실패를 명시적으로 나타내는 '결과 타입'이 있습니다. 나중에 고칠 수 있도록 오류를 기록하는 방법도 보여 줍니다.

기술 내용 (원본 SKILL.md)

작성자의 영어 원문을 GitHub에서 그대로 가져왔습니다.

Error Handling Patterns

Build resilient applications with robust error handling strategies that gracefully handle failures and provide excellent debugging experiences.

When to Use This Skill

  • Implementing error handling in new features
  • Designing error-resilient APIs
  • Debugging production issues
  • Improving application reliability
  • Creating better error messages for users and developers
  • Implementing retry and circuit breaker patterns
  • Handling async/concurrent errors
  • Building fault-tolerant distributed systems

Core Concepts

1. Error Handling Philosophies

Exceptions vs Result Types:

  • Exceptions: Traditional try-catch, disrupts control flow
  • Result Types: Explicit success/failure, functional approach
  • Error Codes: C-style, requires discipline
  • Option/Maybe Types: For nullable values

When to Use Each:

  • Exceptions: Unexpected errors, exceptional conditions
  • Result Types: Expected errors, validation failures
  • Panics/Crashes: Unrecoverable errors, programming bugs

2. Error Categories

Recoverable Errors:

  • Network timeouts
  • Missing files
  • Invalid user input
  • API rate limits

Unrecoverable Errors:

  • Out of memory
  • Stack overflow
  • Programming bugs (null pointer, etc.)

Detailed patterns and worked examples

Detailed pattern documentation lives in references/details.md. Read that file when the navigation tier above is insufficient.

Best Practices

  1. Fail Fast: Validate input early, fail quickly
  2. Preserve Context: Include stack traces, metadata, timestamps
  3. Meaningful Messages: Explain what happened and how to fix it
  4. Log Appropriately: Error = log, expected failure = don't spam logs
  5. Handle at Right Level: Catch where you can meaningfully handle
  6. Clean Up Resources: Use try-finally, context managers, defer
  7. Don't Swallow Errors: Log or re-throw, don't silently ignore
  8. Type-Safe Errors: Use typed errors when possible
# Good error handling example
def process_order(order_id: str) -> Order:
    """Process order with comprehensive error handling."""
    try:
        # Validate input
        if not order_id:
            raise ValidationError("Order ID is required")

        # Fetch order
        order = db.get_order(order_id)
        if not order:
            raise NotFoundError("Order", order_id)

        # Process payment
        try:
            payment_result = payment_service.charge(order.total)
        except PaymentServiceError as e:
            # Log and wrap external service error
            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

        # Update order
        order.status = "completed"
        order.payment_id = payment_result.id
        db.save(order)

        return order

    except ApplicationError:
        # Re-raise known application errors
        raise
    except Exception as e:
        # Log unexpected errors
        logger.exception(f"Unexpected error processing order {order_id}")
        raise ApplicationError(
            "Order processing failed",
            code="INTERNAL_ERROR"
        ) from e

Common Pitfalls

  • Catching Too Broadly: except Exception hides bugs
  • Empty Catch Blocks: Silently swallowing errors
  • Logging and Re-throwing: Creates duplicate log entries
  • Not Cleaning Up: Forgetting to close files, connections
  • Poor Error Messages: "Error occurred" is not helpful
  • Returning Error Codes: Use exceptions or Result types
  • Ignoring Async Errors: Unhandled promise rejections
자주 묻는 질문

'예외'와 '결과 타입'은 무엇이 다른가요?

예외는 정상 흐름을 방해하면서 문제를 처리하게 하는 경고와 같습니다. 결과 타입은 모든 것을 멈추지 않고 작업이 성공했는지 실패했는지 명시적으로 나타내는 방식입니다.

'복구 가능한' 오류와 '복구 불가능한' 오류란 무엇인가요?

복구 가능한 오류는 네트워크 문제처럼 프로그램이 해결을 시도할 수 있는 오류입니다. 복구 불가능한 오류는 메모리 부족처럼 심각해서 보통 프로그램을 멈추게 하는 오류입니다.

오류를 '삼키는(swallow)' 것이 왜 나쁜가요?

오류를 무시하면 문제가 숨겨진 채 남아, 나중에 더 큰 장애로 이어질 수 있습니다. 오류를 기록하거나 발생했음을 알리는 것이 더 좋습니다.

상세 정보

작성자의 원본 설명

Master error handling patterns across languages including exceptions, Result types, error propagation, and graceful degradation to build resilient applications. Use when implementing error handling, designing APIs, or improving application reliability.

repo: wshobson/agents

인기도

GitHub 스타
41k
순위
#6679
라이선스
MIT
업데이트
2026. 10. 15.

이 스킬이 유용한가요?

0

로그인 투표하려면 로그인하세요.

댓글

  • …

이 저장소의 다른 스킬

비슷한 스킬