Chuyển đến nội dung
Skillpedia
Lập trình chung280k · #178

error-handling

Skill này làm gì

Skill này dạy cách xử lý lỗi trong chương trình máy tính. Nó giúp đảm bảo chương trình không bị sập bất ngờ và người dùng nhận được thông báo rõ ràng khi có sự cố.

Khi nào nên dùng

  • ✓Khi tạo một chương trình mới hoặc một phần của chương trình.
  • ✓Khi chương trình cần kết nối tới các dịch vụ khác.
  • ✓Khi suy nghĩ về cách hiển thị thông báo lỗi cho người dùng.

Liên kết skill

https://github.com/affaan-m/ECC/blob/main/pi/core/skills/error-handling/SKILL.md

Sao chép rồi dán vào AI của bạn (Claude, ChatGPT hoặc Cursor) và nhờ nó làm theo hướng dẫn.

Cách dùng

Cách dễ nhất: sao chép tin nhắn và dán vào AI của bạn. AI sẽ đọc skill và làm theo hướng dẫn.

Tin nhắn có sẵn để dán

Hãy dùng skill này để giúp tôi: https://github.com/affaan-m/ECC/blob/main/pi/core/skills/error-handling/SKILL.md Đọc tệp SKILL.md tại liên kết đó và làm theo hướng dẫn cho việc của tôi.
Bạn muốn AI tự tìm những skill như thế này?Cài MCP Skillpedia miễn phí: chỉ một dòng, và AI sẽ tìm trong 15.000+ skill trước mỗi việc.Cài đặt trong 1 phút →

Ví dụ cách nhờ AI

“Làm sao để chương trình của tôi báo cho người dùng một cách lịch sự khi không tìm thấy một mục nào đó?”

5 skill mới mỗi tuần. Đọc chỉ 1 phút.

Cách hoạt động

Nó gợi ý dùng các 'kiểu' lỗi để hiểu chuyện gì đã xảy ra và tạo các thông báo khác nhau cho người dùng và cho lập trình viên. Nó cũng dạy không bỏ qua lỗi và xử lý các thất bại một cách nhất quán.

Nội dung kỹ thuật (SKILL.md gốc)

Lấy nguyên văn từ GitHub, do tác giả viết bằng tiếng Anh.

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

  1. Fail fast and loudly — surface errors at the boundary where they occur; don't bury them
  2. Typed errors over string messages — errors are first-class values with structure
  3. User messages ≠ developer messages — show friendly text to users, log full context server-side
  4. Never swallow errors silently — every catch block must either handle, re-throw, or log
  5. 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


…
Câu hỏi thường gặp

Tại sao xử lý lỗi quan trọng?

Xử lý lỗi giúp chương trình không bị sập, giúp phát hiện vấn đề nhanh chóng và mang lại trải nghiệm tốt hơn nhờ thông báo rõ ràng thay vì những thông báo khó hiểu.

'Typed errors' là gì?

Đây là các lỗi có thông tin có cấu trúc (như mã và thông điệp cụ thể), thay vì chỉ là văn bản thuần. Điều này giúp chương trình hiểu rõ hơn loại vấn đề đang gặp.

Tôi có nên hiển thị cùng một thông báo lỗi cho người dùng và lập trình viên không?

Không. Với người dùng, hãy dùng thông báo đơn giản, thân thiện. Với lập trình viên (trong nhật ký hệ thống chẳng hạn), hãy có chi tiết kỹ thuật để hỗ trợ gỡ lỗi.

Chi tiết

Mô tả gốc của tác giả

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

Độ phổ biến

Sao GitHub
280k
Vị trí xếp hạng
#178
Giấy phép
MIT
Cập nhật
15/10/2026

Skill này có hữu ích không?

0

Đăng nhập để bình chọn.

Bình luận

  • …

Thêm skill từ kho mã này

Skill tương tự