Skills DirectorySkills Directory
SkillsLearnSecurityCategoriesDocsCommunityBlog
Sign InSubmit Skill
Skills Directory

Security-tested agent skills for Claude, coding agents, and AI workflows.

Directory

  • Browse Skills
  • All Skills A–Z
  • Claude Skills
  • Claude Code Skills
  • Agent Skills
  • Categories
  • Submit a Skill

Learn

  • Learn Hub
  • Install Claude Skills
  • Write SKILL.md
  • Skills vs MCP
  • Directories Compared

Security

  • Security
  • Methodology
  • Secure Claude Skills
  • Security Badges

Company

  • About
  • Community
  • Blog
  • API Docs
  • Advertise

2026 Skills Directory. All rights reserved.

Back to skills

Dev Error Handling

ASecurity

Padrões de resilência e error handling para software complexo — retry, circuit breaker, timeouts, error boundaries, logging estruturado.

3 stars
0 votes
0 copies
0 views
Added 9/20/2026
ai-agentstypescriptgoexpressapi

Works with

cliapi

Security Analysis

A100/100

Scanned 9/20/2026

Install to Claude Code

$npx -y skills add joaoguirunas/team-os --skill dev-error-handling --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Dev Error Handling?

Add the live security badge to your README — it updates automatically with every re-scan.

Security grade badge for Dev Error Handling
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/joaoguirunas-dev-error-handling/badge)](https://www.skillsdirectory.com/skills/joaoguirunas-dev-error-handling)

More formats (shields.io, HTML) on the badges page.

Download Zip
Files
SKILL.md
---
name: dev-error-handling
description: Padrões de resilência e error handling para software complexo — retry, circuit breaker, timeouts, error boundaries, logging estruturado.
version: "1.1"
updated: "2026-04-21"
---

# Error Handling & Resilience — Software Complexo

## Princípio fundamental

**Falha é inevitável. Design para falha, não apenas para sucesso.**

Todo código que interage com: banco de dados, APIs externas, filesystem, serviços de terceiros — deve ter error handling explícito.

## Retry com Exponential Backoff

```typescript
async function withRetry<T>(
  fn: () => Promise<T>,
  options: { maxAttempts?: number; baseDelay?: number } = {}
): Promise<T> {
  const { maxAttempts = 3, baseDelay = 300 } = options

  for (let attempt = 1; attempt <= maxAttempts; attempt++) {
    try {
      return await fn()
    } catch (error) {
      if (attempt === maxAttempts) throw error
      // Não fazer retry em erros 4xx (erro do cliente, não transitório)
      if (error.status >= 400 && error.status < 500) throw error

      const delay = baseDelay * Math.pow(2, attempt - 1)  // 300ms, 600ms, 1200ms
      const jitter = Math.random() * 100
      await sleep(delay + jitter)
    }
  }
}

// Uso
const user = await withRetry(() => externalApi.getUser(id), { maxAttempts: 3 })
```

## Timeout Explícito

```typescript
async function withTimeout<T>(promise: Promise<T>, ms: number): Promise<T> {
  const timeout = new Promise<never>((_, reject) =>
    setTimeout(() => reject(new Error(`Timeout after ${ms}ms`)), ms)
  )
  return Promise.race([promise, timeout])
}

// Uso — nunca deixar chamada externa sem timeout
const result = await withTimeout(
  externalApi.processPayment(data),
  5000  // 5 segundos máximo
)
```

## Circuit Breaker

Evita cascata de falhas — para de tentar quando serviço está claramente down.

```typescript
class CircuitBreaker {
  private failures = 0
  private lastFailure?: Date
  private state: 'CLOSED' | 'OPEN' | 'HALF_OPEN' = 'CLOSED'

  constructor(
    private readonly threshold = 5,     // abrir após 5 falhas
    private readonly timeout = 60000    // tentar novamente após 60s
  ) {}

  async execute<T>(fn: () => Promise<T>): Promise<T> {
    if (this.state === 'OPEN') {
      const elapsed = Date.now() - this.lastFailure!.getTime()
      if (elapsed < this.timeout) {
        throw new Error('Circuit breaker is OPEN — service unavailable')
      }
      this.state = 'HALF_OPEN'
    }

    try {
      const result = await fn()
      this.onSuccess()
      return result
    } catch (error) {
      this.onFailure()
      throw error
    }
  }

  private onSuccess() { this.failures = 0; this.state = 'CLOSED' }
  private onFailure() {
    this.failures++
    this.lastFailure = new Date()
    if (this.failures >= this.threshold) this.state = 'OPEN'
  }
}
```

## Error Classes Tipadas

```typescript
// Base
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
  }
}

// Específicos
export class ValidationError extends AppError {
  constructor(details: { field: string; message: string }[]) {
    super('Validation failed', 'VALIDATION_ERROR', 400, details)
  }
}

export class NotFoundError extends AppError {
  constructor(resource: string) {
    super(`${resource} not found`, 'NOT_FOUND', 404)
  }
}

export class ExternalServiceError extends AppError {
  constructor(service: string, cause: Error) {
    super(`${service} failed`, 'EXTERNAL_SERVICE_ERROR', 502)
    this.cause = cause
  }
}
```

## Error Boundary em Express

```typescript
// Handler global — sempre o último middleware
app.use((error: Error, req: Request, res: Response, next: NextFunction) => {
  // Logar com contexto — requestId sempre presente para rastreabilidade
  logger.error({
    err: error,
    requestId: req.requestId,  // gerado pelo middleware de entrada (dev-api-design)
    path: req.path,
    method: req.method,
    userId: req.user?.id,
  }, 'Unhandled error')

  if (error instanceof AppError) {
    return res.status(error.statusCode).json({
      error: {
        code: error.code,
        message: error.message,
        details: error.details,
        requestId: req.requestId,  // sempre incluir na resposta
      }
    })
  }

  // Erro desconhecido — não vazar detalhes internos
  return res.status(500).json({
    error: {
      code: 'INTERNAL_ERROR',
      message: 'An unexpected error occurred',
      requestId: req.requestId,
    }
  })
})
```

## Logging Estruturado

```typescript
import pino from 'pino'

const logger = pino({
  level: process.env.LOG_LEVEL ?? 'info',
  formatters: { level: (label) => ({ level: label }) },
})

// ✅ Correto — requestId sempre presente, contexto rico, sem dados sensíveis
logger.error({
  requestId: req.requestId,  // rastreabilidade end-to-end (ver dev-api-design)
  err: error,
  userId: user.id,
  action: 'payment_process',
  orderId: order.id,
}, 'Payment processing failed')

// ❌ Errado — sem requestId, sem contexto, pode vazar dados sensíveis
console.error('Error:', error)
```

## Graceful Degradation

Quando serviço dependente falha, degradar graciosamente em vez de falhar tudo:

```typescript
async function getUserWithPreferences(userId: string, requestId: string) {
  const user = await db.user.findUnique({ where: { id: userId } })  // crítico
  if (!user) throw new NotFoundError('User')

  // Feature não-crítica — falha silenciosa com fallback
  let preferences = DEFAULT_PREFERENCES
  try {
    preferences = await preferencesService.get(userId)
  } catch (error) {
    logger.warn({
      requestId,      // manter rastreabilidade mesmo no fallback
      userId,
      err: error.message,
    }, 'Failed to load preferences, using defaults')
  }

  return { ...user, preferences }
}
```

## Regras absolutas

- Nunca `catch (e) {}` vazio — sempre logar ou relançar com contexto
- Nunca expor stack traces em respostas de API
- Sempre timeout em chamadas a serviços externos
- Retry apenas em erros transitórios (5xx, network) — nunca em 4xx
- **`requestId` em todos os logs e respostas de erro** — rastreabilidade end-to-end
- Erros devem ter contexto suficiente para debug sem reprodução

Attribution

joaoguirunasjoaoguirunas
View sourceMore from joaoguirunas →
SSkills DirectorySkills Directory

Your tool, in front of Claude Code builders.

3 founder slots · $299/mo · GSC-verified traffic · sponsors can never buy grades.

See placements

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

Comments (0)

No comments yet. Be the first to comment!

SSkills DirectorySkills Directory

Your tool, in front of Claude Code builders.

3 founder slots · $299/mo · GSC-verified traffic · sponsors can never buy grades.

See placements

Related Skills

Caveman

Ultra-compressed communication mode. Cuts token usage ~75% by speaking like caveman while keeping full technical accuracy. Supports intensity levels: lite, full (default), ultra, wenyan-lite, wenyan-full, wenyan-ultra. Use when user says "caveman mode", "talk like caveman", "use caveman", "less tokens", "be brief", or invokes /caveman. Also auto-triggers when token efficiency is requested.

1023331 votes

Hyperplan

Adversarial multi-agent planning skill. Self-orchestrates 5 hostile category members (unspecified-low, unspecified-high, deep, ultrabrain, artistry) via team-mode for ruthless cross-critique debate, distills only the defensible insights, then MANDATORILY hands the distilled insight bundle to the `plan` agent for executable plan formalization. Use when planning needs maximum rigor and surfacing of weak assumptions, blind spots, and over-engineering. Triggers: 'hyperplan', 'hpp', '/hyperplan', ...

686011 votes

Mcp Code Execution

Routes multi-tool workflows through MCP servers for large datasets and pipelines. Use when Bash tool overhead is limiting throughput on data-heavy tasks.

3331 votes

catchup

Recovers prior coding-agent session context by running `catchup <agent> --since-compact`, which extracts a clean summary of a previous Codex, Claude Code, Antigravity, OpenCode, or Pi Agent session. Use when the user says "catch up", "what did the last session do", "get me up to speed", "I switched agents", or asks to recover/summarize a previous session before continuing. Do NOT use for the current conversation, git history, or any non-agent log.

611 votes

math-skill

A comprehensive mathematical reasoning skill for AI assistants — handles arithmetic to research-level problems with rigorous step-by-step reasoning, systematic verification, and transparent uncertainty handling

381 votes
View all in ai-agents →