Communitygithub.com

Tratamento de Erros

Padrões para tratamento robusto de erros em TypeScript, Python e Go. Abrange erros tipados, limites de erro, retentativas, disjuntores e mensagens de erro voltadas ao usuário. Use ao projetar tipos de erro, retentativas, disjuntores ou mensagens de falha voltadas ao usuário em TypeScript, Python ou Go.

O que é Tratamento de Erros?

Este skill fornece padrões consistentes e robustos de tratamento de erros para aplicações de produção, com suporte para TypeScript, Python e Go. Ele ajuda desenvolvedores a projetar hierarquias de erro tipadas, implementar lógica de retentativa com backoff exponencial, criar limites de erro em React e gerenciar mensagens de erro voltadas ao usuário separadas de detalhes técnicos internos. O skill cobre princípios como 'falhe rápido e alto', erros tipados em vez de strings soltas, e a distinção entre mensagens para usuários e para desenvolvedores. É útil ao projetar novos módulos, adicionar resiliência a dependências externas, revisar APIs para tratamento de falhas ausente e depurar falhas em cascata. As plataformas suportadas incluem TypeScript/JavaScript (com classes de erro, padrão Result, manipuladores de API Next.js/Express e limites de erro React), Python (com hierarquia de exceções e manipulador global FastAPI) e Go (com erros sentinela, wrapping e switch de tratamento em handlers).

Funciona com~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/affaan-m/ECC/tree/main/skills/error-handling

Perguntar na sua IA favorita

Abre um novo chat com esta habilidade de agente já pré-carregada.

Documentação

Padrões de Tratamento de Erros

Padrões consistentes e robustos de tratamento de erros para aplicações de produção.

Quando Ativar

  • Projetar hierarquias de erro ou exceções para um novo módulo ou serviço
  • Adicionar lógica de retentativa ou disjuntores para dependências externas não confiáveis
  • Revisar endpoints de API em busca de tratamento de erro ausente
  • Implementar mensagens de erro voltadas ao usuário e feedback
  • Depurar falhas em cascata ou supressão silenciosa de erros

Princípios Fundamentais

  1. Falhe rápido e alto — superfcie erros no limite onde ocorrem; não os enterre
  2. Erros tipados em vez de mensagens string — erros são valores de primeira classe com estrutura
  3. Mensagens para usuário ≠ mensagens para desenvolvedor — mostre texto amigável aos usuários, registre contexto completo no servidor
  4. Nunca suprima erros silenciosamente — todo bloco catch deve tratar, relançar ou registrar
  5. Erros são parte do seu contrato de API — documente cada código de erro que um cliente pode receber

TypeScript / JavaScript

Classes de Erro Tipadas

// Defina uma hierarquia de erro para seu domínio
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
    // Mantém a cadeia de protótipo correta em JavaScript ES5 transpilado.
    // Necessário para que verificações `instanceof` (ex.: `error instanceof NotFoundError`)
    // funcionem corretamente ao estender a classe Error nativa.
    Object.setPrototypeOf(this, new.target.prototype)
  }
}

export class NotFoundError extends AppError {
  constructor(resource: string, id: string) {
    super(`${resource} não encontrado: ${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 = 'Autenticação necessária') {
    super(reason, 'UNAUTHORIZED', 401)
  }
}

export class RateLimitError extends AppError {
  constructor(public readonly retryAfterMs: number) {
    super('Limite de requisições excedido', 'RATE_LIMITED', 429)
  }
}

Padrão de Resultado (estilo sem throw)

Para operações onde a falha é esperada e comum (análise sintática, chamadas externas):

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 }
}

// Uso
async function fetchUser(id: string): Promise<Result<User>> {
  try {
    const user = await db.users.findUnique({ where: { id } })
    if (!user) return err(new NotFoundError('Usuário', id))
    return ok(user)
  } catch (e) {
    return err(new AppError('Erro no banco de dados', 'DB_ERROR'))
  }
}

const result = await fetchUser('abc-123')
if (!result.ok) {
  // TypeScript sabe que result.error está aqui
  logger.error('Falha ao buscar usuário', { error: result.error })
  return
}
// TypeScript sabe que result.value está aqui
console.log(result.value.email)

Manipulador de Erro de API (Next.js / Express)

import { NextRequest, NextResponse } from 'next/server'

function handleApiError(error: unknown): NextResponse {
  // Erro de aplicação conhecido
  if (error instanceof AppError) {
    return NextResponse.json(
      {
        error: {
          code: error.code,
          message: error.message,
          ...(error.details ? { details: error.details } : {}),
        },
      },
      { status: error.statusCode },
    )
  }

  // Erro de validação Zod
  if (error instanceof z.ZodError) {
    return NextResponse.json(
      {
        error: {
          code: 'VALIDATION_ERROR',
          message: 'Falha na validação da requisição',
          details: error.issues.map(i => ({
            field: i.path.join('.'),
            message: i.message,
          })),
        },
      },
      { status: 422 },
    )
  }

  // Erro inesperado — registre detalhes, retorne mensagem genérica
  console.error('Erro inesperado:', error)
  return NextResponse.json(
    { error: { code: 'INTERNAL_ERROR', message: 'Ocorreu um erro inesperado' } },
    { status: 500 },
  )
}

export async function POST(req: NextRequest) {
  try {
    // ... lógica do manipulador
  } catch (error) {
    return handleApiError(error)
  }
}

Limite de Erro React

import { Component, ErrorInfo, ReactNode } from 'react'

interface Props {
  fallback: ReactNode
  onError?: (error: Error, info: ErrorInfo) => void
  children: ReactNode
}

interface State {
  hasError: boolean
  error: Error | null
}

export class ErrorBoundary extends Component<Props, State> {
  state: State = { hasError: false, error: null }

  static getDerivedStateFromError(error: Error): State {
    return { hasError: true, error }
  }

  componentDidCatch(error: Error, info: ErrorInfo) {
    this.props.onError?.(error, info)
    console.error('Erro não tratado no React:', error, info)
  }

  render() {
    if (this.state.hasError) return this.props.fallback
    return this.props.children
  }
}

// Uso
<ErrorBoundary fallback={<p>Algo deu errado. Atualize a página.</p>}>
  <MyComponent />
</ErrorBoundary>

Python

Hierarquia de Exceções Personalizadas

class AppError(Exception):
    """Erro base da aplicação."""
    def __init__(self, message: str, code: str, status_code: int = 500):
        super().__init__(message)
        self.code = code
        self.status_code = status_code

class NotFoundError(AppError):
    def __init__(self, resource: str, id: str):
        super().__init__(f"{resource} não encontrado: {id}", "NOT_FOUND", 404)

class ValidationError(AppError):
    def __init__(self, message: str, details: list[dict] | None = None):
        super().__init__(message, "VALIDATION_ERROR", 422)
        self.details = details or []

Manipulador Global de Exceções FastAPI

from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse

app = FastAPI()

@app.exception_handler(AppError)
async def app_error_handler(request: Request, exc: AppError) -> JSONResponse:
    return JSONResponse(
        status_code=exc.status_code,
        content={"error": {"code": exc.code, "message": str(exc)}},
    )

@app.exception_handler(Exception)
async def generic_error_handler(request: Request, exc: Exception) -> JSONResponse:
    # Registre detalhes completos, retorne mensagem genérica
    logger.exception("Erro inesperado", exc_info=exc)
    return JSONResponse(
        status_code=500,
        content={"error": {"code": "INTERNAL_ERROR", "message": "Ocorreu um erro inesperado"}},
    )

Go

Erros Sentinelas e Wrapping de Erros

package domain

import "errors"

// Erros sentinelas para verificação de tipo
var (
    ErrNotFound    = errors.New("não encontrado")
    ErrUnauthorized = errors.New("não autorizado")
    ErrConflict     = errors.New("conflito")
)

// Empacote erros com contexto — nunca perca o original
func (r *UserRepository) FindByID(ctx context.Context, id string) (*User, error) {
    user, err := r.db.QueryRow(ctx, "SELECT * FROM users WHERE id = $1", id)
    if errors.Is(err, sql.ErrNoRows) {
        return nil, fmt.Errorf("usuário %s: %w", id, ErrNotFound)
    }
    if err != nil {
        return nil, fmt.Errorf("consultando usuário %s: %w", id, err)
    }
    return user, nil
}

// No nível do handler, desempacote para determinar a resposta
func (h *Handler) GetUser(w http.ResponseWriter, r *http.Request) {
    user, err := h.service.GetUser(r.Context(), chi.URLParam(r, "id"))
    if err != nil {
        switch {
        case errors.Is(err, domain.ErrNotFound):
            writeError(w, http.StatusNotFound, "not_found", err.Error())
        case errors.Is(err, domain.ErrUnauthorized):
            writeError(w, http.StatusForbidden, "forbidden", "Acesso negado")
        default:
            slog.Error("erro inesperado", "err", err)
            writeError(w, http.StatusInternalServerError, "internal_error", "Ocorreu um erro inesperado")
        }
        return
    }
    writeJSON(w, http.StatusOK, user)
}

Retentativa com Backoff Exponencial

interface RetryOptions {
  maxAttempts?: number
  baseDelayMs?: number
  maxDelayMs?: number
  retryIf?: (error: unknown) => boolean
}

async function withRetry<T>(
  fn: () => Promise<T>,
  options: RetryOptions = {},
): Promise<T> {
  const {
    maxAttempts = 3,
    baseDelayMs = 500,
    maxDelayMs = 10_000,
    retryIf = () => true,
  } = options

  let lastError: unknown

  for (let attempt = 1; attempt <= maxAttempts; attempt++) {
    try {
      return await fn()
    } catch (error) {
      lastError = error
      if (attempt === maxAttempts || !retryIf(error)) throw error

      const jitter = Math.random() * baseDelayMs
      const delay = Math.min(baseDelayMs * 2 ** (attempt - 1) + jitter, maxDelayMs)
      await new Promise(resolve => setTimeout(resolve, delay))
    }
  }

  throw lastError
}

// Uso: tente novamente erros de rede transitórios, não 4xx
const data = await withRetry(() => fetch('/api/data').then(r => r.json()), {
  maxAttempts: 3,
  retryIf: (error) => !(error instanceof AppError && error.statusCode < 500),
})

Mensagens de Erro Voltadas ao Usuário

Mapeie códigos de erro para mensagens legíveis. Mantenha detalhes técnicos fora do texto visível ao usuário.

const USER_ERROR_MESSAGES: Record<string, string> = {
  NOT_FOUND: 'O item solicitado não foi encontrado.',
  UNAUTHORIZED: 'Faça login para continuar.',
  FORBIDDEN: 'Você não tem permissão para fazer isso.',
  VALIDATION_ERROR: 'Verifique sua entrada e tente novamente.',
  RATE_LIMITED: 'Muitas requisições. Aguarde um momento e tente novamente.',
  INTERNAL_ERROR: 'Algo deu errado em nosso sistema. Tente novamente mais tarde.',
}

export function getUserMessage(code: string): string {
  return USER_ERROR_MESSAGES[code] ?? USER_ERROR_MESSAGES.INTERNAL_ERROR
}

Lista de Verificação de Tratamento de Erros

Antes de mesclar qualquer código que toque em tratamento de erros:

  • Todo bloco catch trata, relança ou registra — sem supressão silenciosa
  • Erros de API seguem o formato padrão { error: { code, message } }
  • Mensagens voltadas ao usuário não contêm stack traces ou detalhes internos
  • Contexto completo do erro registrado no servidor
  • Classes de erro personalizadas estendem uma base AppError com campo code
  • Funções assíncronas superam erros para os chamadores — sem fire-and-forget sem fallback
  • Lógica de retentativa tenta apenas erros retentáveis (não erros 4xx do cliente)
  • Componentes React são envolvidos em ErrorBoundary para erros de renderização

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

accessibility

Design, implement, and audit inclusive digital products using WCAG 2.2 Level AA. Use when building or auditing UI that must meet WCAG 2.2 Level AA, or when reviewing a change for keyboard, contrast, or screen-reader support.

affaan-m/content-engine

Create platform-native content systems for X, LinkedIn, TikTok, YouTube, newsletters, and repurposed multi-platform campaigns. Use when the user wants social posts, threads, scripts, content calendars, or one source asset adapted cleanly across platforms.

affaan-m/ECC

Multi-platform content distribution across X, LinkedIn, Threads, and Bluesky. Adapts content per platform using content-engine patterns. Never posts identical content cross-platform. Use when the user wants to distribute content across social platforms.

affaan-m/fal-ai-media

Unified media generation via fal.ai MCP — image, video, and audio. Covers text-to-image (Nano Banana), text/image-to-video (Seedance, Kling, Veo 3), text-to-speech (CSM-1B), and video-to-audio (ThinkSound). Use when the user wants to generate images, videos, or audio with AI.

affaan-m/manim-video

日本語翻訳:このファイルは manim-video 用の日本語翻訳が必要です

affaan-m/remotion-video-creation

Remotion のベストプラクティス - React で動画を作成する。3D、アニメーション、音声、字幕、チャート、トランジションなどをカバーするドメイン固有の29のルール。

affaan-m/video-editing

AI-assisted video editing workflows for cutting, structuring, and augmenting real footage. Covers the full pipeline from raw capture through FFmpeg, Remotion, ElevenLabs, fal.ai, and final polish in Descript or CapCut. Use when the user wants to edit video, cut footage, create vlogs, or build video content.

agent-architecture-audit

Full-stack diagnostic for agent and LLM applications. Audits the 12-layer agent stack for wrapper regression, memory pollution, tool discipline failures, hidden repair loops, and rendering corruption. Produces severity-ranked findings with code-first fixes. Essential for developers building agent applications, autonomous loops, or any LLM-powered feature. Use when an agent or LLM feature misbehaves and the failing layer is unknown, or before shipping an agent stack.

agent-eval

Head-to-head comparison of coding agents (Claude Code, Aider, Codex, etc.) on custom tasks with pass rate, cost, time, and consistency metrics. Use when choosing between coding agents, or when a change to an agent setup needs measured pass rate, cost, and time rather than an impression.

agent-harness-construction

Design and optimize AI agent action spaces, tool definitions, and observation formatting for higher completion rates. Use when defining or revising an agent

agentic-engineering

Operate as an agentic engineer using eval-first execution, decomposition, and cost-aware model routing. Use when planning or executing engineering work that agents will carry out end to end.

agentic-os

Build persistent multi-agent operating systems on Claude Code. Covers kernel architecture, specialist agents, slash commands, file-based memory, scheduled automation, and state management without external databases. Use when building a persistent multi-agent system on Claude Code with its own memory, commands, and scheduling.

agent-introspection-debugging

Structured self-debugging workflow for AI agent failures using capture, diagnosis, contained recovery, and introspection reports. Use when an agent run fails and you need a reproducible diagnosis instead of a retry.

agent-payment-x402

Add x402 payment execution to AI agents with per-task budgets, spending controls, and non-custodial wallets. Supports Base through agentwallet-sdk and X Layer through OKX Payments / OKX Agent Payments Protocol. Use when an agent must pay for something itself and needs per-task budgets, spending controls, and a non-custodial wallet.

agent-self-evaluation

Use after completing any non-trivial task. The agent self-rates its output on 5 axes — accuracy, completeness, clarity, actionability, conciseness — with concrete evidence per criterion. Produces a structured 1-5 scorecard with specific improvement suggestions.

agent-sort

Build an evidence-backed ECC install plan for a specific repo by sorting skills, commands, rules, hooks, and extras into DAILY vs LIBRARY buckets using parallel repo-aware review passes. Use when ECC should be trimmed to what a project actually needs instead of loading the full bundle.

ai-first-engineering

Engineering operating model for teams where AI agents generate a large share of implementation output. Use when setting team process, review gates, or ownership rules for a codebase largely written by agents.

ai-regression-testing

Regression testing strategies for AI-assisted development. Sandbox-mode API testing without database dependencies, automated bug-check workflows, and patterns to catch AI blind spots where the same model writes and reviews code. Use when adding regression coverage to AI-assisted code, or when the same model both wrote and reviewed a change.

android-clean-architecture

Clean Architecture patterns for Android and Kotlin Multiplatform projects — module structure, dependency rules, UseCases, Repositories, and data layer patterns. Use when structuring modules, layers, or data flow in an Android or KMP project.

angular-developer

Generates Angular code and provides architectural guidance. Trigger when creating projects, components, or services, or for best practices on reactivity (signals, linkedSignal, resource), forms, dependency injection, routing, SSR, accessibility (ARIA), animations, styling (component styles, Tailwind CSS), testing, or CLI tooling.

Habilidades Relacionadas