error-handling
하는 일
이 스킬은 컴퓨터 프로그램에서 오류를 처리하는 방법을 가르칩니다. 프로그램이 예고 없이 멈추지 않도록 하고, 무언가 잘못되었을 때 사용자가 명확한 메시지를 받도록 돕습니다.
사용하는 경우
- ✓새 프로그램이나 그 일부를 만들 때.
- ✓프로그램이 다른 서비스에 연결해야 할 때.
- ✓사용자에게 오류 메시지를 어떻게 보여 줄지 고민할 때.
스킬 링크
https://github.com/affaan-m/ECC/blob/main/pi/core/skills/error-handling/SKILL.md복사해서 AI(Claude, ChatGPT, Cursor)에 붙여넣고 지침을 따르도록 요청하세요.
사용 방법
가장 쉬운 방법입니다. 메시지를 복사해 AI에 붙여넣으세요. AI가 스킬을 읽고 지침을 따릅니다.
바로 붙여넣을 수 있는 메시지
Claude Code, Codex, Cursor용입니다. 프로젝트 폴더에서 실행하면 스킬이 설치됩니다.
SKILL.md를 다운로드해 에이전트의 스킬 폴더에 넣으세요.
AI에게 요청하는 예시
“찾는 항목이 없을 때 프로그램이 사용자에게 친절하게 알리도록 하려면 어떻게 해야 하나요?”
매주 새 스킬 5개. 읽는 데 1분.
작동 방식
오류의 '타입'을 써서 무슨 일이 일어났는지 이해하고, 사용자용 메시지와 개발자용 메시지를 따로 만들라고 제안합니다. 또한 오류를 무시하지 말고, 실패를 일관되게 처리하라고 가르칩니다.
기술 내용 (원본 SKILL.md)
작성자의 영어 원문을 GitHub에서 그대로 가져왔습니다.
Error Handling Patterns
Consistent, robust error handling patterns for production applications.
When to Activate
- Designing error types or exception hierarchies for a new module or service
- Adding retry logic or circuit breakers for unreliable external dependencies
- Reviewing API endpoints for missing error handling
- Implementing user-facing error messages and feedback
- Debugging cascading failures or silent error swallowing
Core Principles
- Fail fast and loudly — surface errors at the boundary where they occur; don't bury them
- Typed errors over string messages — errors are first-class values with structure
- User messages ≠ developer messages — show friendly text to users, log full context server-side
- Never swallow errors silently — every
catchblock must either handle, re-throw, or log - Errors are part of your API contract — document every error code a client may receive
TypeScript / JavaScript
Typed Error Classes
// Define an error hierarchy for your domain
export class AppError extends Error {
constructor(
message: string,
public readonly code: string,
public readonly statusCode: number = 500,
public readonly details?: unknown,
) {
super(message)
this.name = this.constructor.name
// Maintain correct prototype chain in transpiled ES5 JavaScript.
// Required for `instanceof` checks (e.g., `error instanceof NotFoundError`)
// to work correctly when extending the built-in Error class.
Object.setPrototypeOf(this, new.target.prototype)
}
}
export class NotFoundError extends AppError {
constructor(resource: string, id: string) {
super(`${resource} not found: ${id}`, 'NOT_FOUND', 404)
}
}
export class ValidationError extends AppError {
constructor(message: string, details: { field: string; message: string }[]) {
super(message, 'VALIDATION_ERROR', 422, details)
}
}
export class UnauthorizedError extends AppError {
constructor(reason = 'Authentication required') {
super(reason, 'UNAUTHORIZED', 401)
}
}
export class RateLimitError extends AppError {
constructor(public readonly retryAfterMs: number) {
super('Rate limit exceeded', 'RATE_LIMITED', 429)
}
}
Result Pattern (no-throw style)
For operations where failure is expected and common (parsing, external calls):
type Result<T, E = AppError> =
| { ok: true; value: T }
| { ok: false; error: E }
function ok<T>(value: T): Result<T> {
return { ok: true, value }
}
function err<E>(error: E): Result<never, E> {
return { ok: false, error }
}
// Usage
async function fetchUser(id: string): Promise<Result<User>> {
try {
const user = await db.users.findUnique({ where: { id } })
if (!user) return err(new NotFoundError('User', id))
return ok(user)
} catch (e) {
return err(new AppError('Database error', 'DB_ERROR'))
}
}
const result = await fetchUser('abc-123')
if (!result.ok) {
// TypeScript knows result.error here
logger.error('Failed to fetch user', { error: result.error })
return
}
// TypeScript knows result.value here
console.log(result.value.email)
API Error Handler (Next.js / Express)
import { NextRequest, NextResponse } from 'next/server'
function handleApiError(error: unknown): NextResponse {
// Known application error
if (error instanceof AppError) {
return NextResponse.json(
{
error: {
code: error.code,
message: error.message,
...(error.details ? { details: error.details } : {}),
},
},
{ status: error.statusCode },
)
}
// Zod validation error
if (error instanceof z.ZodError) {
return NextResponse.json(
{
error: {
code: 'VALIDATION_ERROR',
message: 'Request validation failed',
details: error.issues.map(i => ({
field: i.path.join('.'),
message: i.message,
})),
},
},
{ status: 422 },
)
}
// Unexpected error — log details, return generic message
console.error('Unexpected error:', error)
return NextResponse.json(
{ error: { code: 'INTERNAL_ERROR', message: 'An unexpected error occurred' } },
{ status: 500 },
)
}
export async function POST(req: NextRequest) {
try {
// ... handler logic
} catch (error) {
return handleApiError(error)
}
}
React Error Boundary
…
자주 묻는 질문
오류 처리가 왜 중요한가요?
오류를 처리하면 프로그램이 멈추는 것을 막고, 문제를 빨리 찾을 수 있으며, 혼란스러운 메시지 대신 명확한 피드백을 주어 더 나은 사용자 경험을 제공합니다.
'타입이 있는 오류'란 무엇인가요?
단순한 텍스트가 아니라, 구조화된 정보(특정 코드와 메시지 등)를 가진 오류입니다. 프로그램이 문제의 종류를 더 잘 이해하게 돕습니다.
같은 오류 메시지를 사용자와 개발자에게 모두 보여 줘야 할까요?
아닙니다. 사용자에게는 간단하고 친절한 메시지를, 개발자에게는(예: 로그에) 디버깅에 도움이 되는 기술적 세부 정보를 보여 주세요.
상세 정보
작성자의 원본 설명
Patterns for robust error handling across TypeScript, Python, and Go. Covers typed errors, error boundaries, retries, circuit breakers, and user-facing error messages. Use when designing error types, retries, circuit breakers, or user-facing failure messages in TypeScript, Python, or Go.
repo: affaan-m/ECC
인기도
- GitHub 스타
- 280k
- 순위
- #178
- 라이선스
- MIT
- 업데이트
- 2026. 10. 15.
댓글
- …
이 저장소의 다른 스킬
accessibility
280k에이전트가 모든 사람이 쓸 수 있는 인터페이스를 만들도록 돕습니다. 시각 장애나 운동 장애가 있는 사람도 쓸 수 있게 합니다.
agent-architecture-audit
280k에이전트가 모든 것이 올바르게 작동하는지 점검하도록 돕습니다. AI 시스템의 문제를 찾아 고쳐서 기대대로 작동하게 합니다.
agent-eval
280k에이전트가 서로 다른 AI 코딩 도구를 비교하도록 돕습니다. 특정 작업에서 어느 도구가 더 빠르고, 저렴하고, 믿을 만한지 측정합니다.
agent-harness-construction
280k에이전트가 작업을 더 잘 이해하도록 돕습니다. 에이전트가 쓰는 도구와 지시문을 최적화해 성공 가능성을 높입니다.