본문으로 건너뛰기
cccskills
무료GitHub에 공개

error-handling

Error handling patterns for API endpoints. Use when implementing error handling, writing middleware, or reviewing how errors are caught and formatted in API code.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

설치 방법 보기

포함된 파일(1)

  • SKILL.md5.6 KB

SKILL.md(원문)

설치하기 전에 에이전트에게 전달되는 지시 내용을 확인할 수 있습니다.

These patterns apply to all API endpoint handlers in this codebase. Every error must be handled explicitly — no unhandled exceptions may reach the HTTP framework.

Fundamental rule

All errors are caught and formatted at the handler level (or in a central error-handling middleware/decorator that wraps every handler). The framework never renders an unhandled exception as a response.

Central error handling

Use the shared error-handling decorator or middleware for every handler. Do not write try/catch blocks that format HTTP responses directly inside business logic. The pattern:

request → auth middleware → handler → error middleware → formatted response

If the handler throws, the error middleware intercepts it, logs it if appropriate, and converts it to the standard error envelope before sending the response.

Logging rules

Log 5xx errors (unexpected server errors) at the ERROR level with:

  • Request ID (from the X-Request-ID header, or generate one if absent)
  • Error message
  • Full stack trace
  • Request method and path (not the full URL — avoid logging query parameters that may contain tokens)

Do not log 4xx errors at ERROR level. Log them at DEBUG level if useful for debugging, but 4xx errors are expected client behavior and should not generate noise in error monitoring.

Never log request bodies or response bodies unless explicitly enabled for debugging in a non-production environment.

What belongs in API responses

Never include in an API error response:

  • Stack traces
  • SQL queries or database error messages
  • Internal file paths
  • Environment variable names or values
  • Dependency version strings

Always include:

  • A stable code in SCREAMING_SNAKE_CASE
  • A human-readable message safe for end users

Mapping error types to status codes

Input validation errors → 422

Use 422 when the request is syntactically valid but semantically invalid (missing required fields, wrong value format, business rule violation detectable before touching external state).

{
  "error": {
    "code": "VALIDATION_FAILED",
    "message": "One or more fields failed validation.",
    "details": {
      "fields": [
        { "field": "email", "message": "Must be a valid email address." }
      ]
    }
  }
}

Authentication errors → 401

Use 401 when the request has no token, the token is expired, or the token is invalid. The message should not indicate which of these conditions applies — treat them identically to avoid enumeration attacks.

{
  "error": {
    "code": "UNAUTHENTICATED",
    "message": "Authentication is required to access this resource."
  }
}

Authorization errors → 403

Use 403 when the user is authenticated but does not have permission to perform the action. Use a consistent message that does not reveal whether the resource exists.

{
  "error": {
    "code": "FORBIDDEN",
    "message": "You do not have permission to perform this action."
  }
}

Resource not found → 404

Use 404 when a resource addressed by ID does not exist or has been deleted. If the user does not have permission to know whether the resource exists, return 403 instead of 404.

{
  "error": {
    "code": "NOT_FOUND",
    "message": "The requested resource was not found."
  }
}

Database constraint violations → 409 or 422

  • Unique constraint violation (e.g., email already taken) → 409 Conflict
  • Foreign key violation that reveals a missing parent resource → 422 Validation Failed
  • Do not let raw database error messages propagate — catch them in the data layer and convert them before they reach the handler
{
  "error": {
    "code": "CONFLICT",
    "message": "A user with this email address already exists."
  }
}

Timeouts → 503

Use 503 when a downstream dependency (database, external API) times out. Include a Retry-After header with a suggested retry delay in seconds.

{
  "error": {
    "code": "SERVICE_UNAVAILABLE",
    "message": "The service is temporarily unavailable. Please try again shortly."
  }
}

Response header: Retry-After: 30

Rate limiting → 429

Use 429 when the client has exceeded the rate limit. Include Retry-After and X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset headers.

{
  "error": {
    "code": "RATE_LIMITED",
    "message": "Too many requests. Please slow down."
  }
}

Unknown errors → 500

All other unhandled exceptions become 500. The response body contains only a generic message. The real error is logged internally.

{
  "error": {
    "code": "INTERNAL_ERROR",
    "message": "An unexpected error occurred. If this persists, contact support."
  }
}

An internal alert must fire for every 500 response in production. Do not let 500 errors go undetected.

Error codes reference

CodeStatusMeaning
VALIDATION_FAILED422One or more input fields failed validation
UNAUTHENTICATED401Missing or invalid authentication token
FORBIDDEN403Authenticated but not authorized
NOT_FOUND404Resource does not exist
CONFLICT409Resource already exists or state conflict
RATE_LIMITED429Client exceeded rate limit
SERVICE_UNAVAILABLE503Downstream timeout or unavailability
INTERNAL_ERROR500Unexpected server error

Use these codes consistently. Do not create one-off codes for situations already covered here.

리뷰

아직 리뷰가 없습니다. 사용해 본 소감을 남겨 주세요.

댓글

로그인 없이 쓸 수 있습니다. 사용 후기, 질문, 작동하지 않은 환경 등을 편하게 남겨 주세요.

아직 댓글이 없습니다. 첫 댓글을 남겨 보세요.

보내면 바로 공개됩니다. 이메일 주소나 전화번호 같은 개인 정보는 쓰지 마세요. URL은 2개까지입니다.

0 / 1,000자

이 양식은 reCAPTCHA로 보호되며 Google 개인정보처리방침 및 서비스 약관이 적용됩니다.

같은 저장소의 스킬

Write an Architecture Decision Record (ADR) document for a technical decision. Use when documenting a technical choice, architectural decision, or design decision.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

davila7/claude-with-skills132026년 5월 15일 업데이트

REST API design conventions for this codebase. Use when writing or reviewing API endpoints, route definitions, response formatting, or client code that calls the API.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

davila7/claude-with-skills132026년 5월 15일 업데이트

Automatically format code files after every edit using Prettier and ESLint. Active in the background whenever Claude edits a file. Formatting is silent — no prompts, no output unless a formatter fails. Use when you want consistent formatting enforced automatically during a coding session.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

davila7/claude-with-skills132026년 5월 15일 업데이트

Create a git branch named after a GitHub issue.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

davila7/claude-with-skills132026년 5월 15일 업데이트

Draft a CHANGELOG.md entry for the current changes in Keep a Changelog format. Use when releasing, tagging a version, or updating CHANGELOG.md.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

davila7/claude-with-skills132026년 5월 15일 업데이트

Draft the changelog entry for all unreleased commits in Keep a Changelog format. Groups commits into Added, Changed, Fixed, Removed, and Security. Use before releasing a new version or when updating CHANGELOG.md.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

davila7/claude-with-skills132026년 5월 15일 업데이트

davila7의 스킬 모두 보기

이 스킬의 문제 신고