AutomationFlowsAI & RAG › Auto-fix Production Errors with Claude

Auto-fix Production Errors with Claude

Auto-Fix Production Errors with Claude. Uses anthropic, httpRequest, slack, emailSend. Webhook trigger; 10 nodes.

Webhook trigger★★★★☆ complexityAI-powered10 nodesAnthropicHTTP RequestSlackEmail Send
AI & RAG Trigger: Webhook Nodes: 10 Complexity: ★★★★☆ AI nodes: yes Added:

This workflow follows the Emailsend → HTTP Request recipe pattern — see all workflows that pair these two integrations.

The workflow JSON

Copy or download the full n8n JSON below. Paste it into a new n8n workflow, add your credentials, activate. Full import guide →

Download .json
{
  "name": "Auto-Fix Production Errors with Claude",
  "nodes": [
    {
      "parameters": {
        "httpMethod": "POST",
        "path": "flare-webhook",
        "responseMode": "lastNode",
        "options": {}
      },
      "id": "webhook-flare",
      "name": "Webhook - Flare Error",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 1,
      "position": [
        250,
        300
      ]
    },
    {
      "parameters": {
        "functionCode": "// Extrai informa\u00e7\u00f5es do erro do Flare\nconst error = items[0].json;\n\nconst errorData = {\n  exception: error.exception?.class || 'Unknown',\n  message: error.exception?.message || 'No message',\n  file: error.exception?.file || '',\n  line: error.exception?.line || 0,\n  trace: error.exception?.trace?.slice(0, 5) || [],\n  context: error.context || {},\n  environment: error.context?.env || 'production',\n  timestamp: new Date().toISOString(),\n  url: error.request?.url || '',\n  method: error.request?.method || '',\n  tenant_id: error.context?.tenant_id || null,\n  tenant_name: error.context?.tenant_name || null\n};\n\nreturn {\n  json: {\n    error: errorData,\n    prompt: `ERRO DE PRODU\u00c7\u00c3O NO YUMGO:\n\nExce\u00e7\u00e3o: ${errorData.exception}\nMensagem: ${errorData.message}\nArquivo: ${errorData.file}:${errorData.line}\nURL: ${errorData.url}\nTenant: ${errorData.tenant_name || 'Central'}\n\nStack Trace:\n${errorData.trace.map((t, i) => `${i+1}. ${t.class}@${t.method} (${t.file}:${t.line})`).join('\\n')}\n\nANALISE:\n1. Identifique a causa raiz\n2. Sugira a corre\u00e7\u00e3o necess\u00e1ria\n3. Forne\u00e7a o c\u00f3digo corrigido se poss\u00edvel\n4. Indique se \u00e9 cr\u00edtico ou pode esperar\n\nResposta em formato JSON:\n{\n  \"severity\": \"critical|high|medium|low\",\n  \"cause\": \"descri\u00e7\u00e3o da causa\",\n  \"solution\": \"descri\u00e7\u00e3o da solu\u00e7\u00e3o\",\n  \"code_fix\": \"c\u00f3digo corrigido (se aplic\u00e1vel)\",\n  \"file_path\": \"caminho do arquivo a corrigir\",\n  \"can_auto_fix\": true|false\n}`\n  }\n};"
      },
      "id": "extract-error",
      "name": "Extract Error Data",
      "type": "n8n-nodes-base.function",
      "typeVersion": 1,
      "position": [
        450,
        300
      ]
    },
    {
      "parameters": {
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "anthropicApi",
        "resource": "message",
        "model": "claude-sonnet-4-20250514",
        "text": "={{ $json.prompt }}",
        "options": {
          "maxTokens": 4000,
          "temperature": 0.3,
          "systemPrompt": "Voc\u00ea \u00e9 um assistente especializado em corrigir erros de produ\u00e7\u00e3o no YumGo (sistema Laravel 11 de delivery multi-tenant).\n\n# REGRAS CR\u00cdTICAS DO PROJETO\n\n## Multi-Tenant (PostgreSQL Schemas)\n- NUNCA misture dados entre tenants - cada restaurante tem schema isolado\n- SEMPRE verifique se tenancy est\u00e1 inicializado antes de queries\n- Schema PUBLIC = plataforma (tenants, plans, subscriptions)\n- Schema TENANT_* = dados do restaurante (customers, orders, products)\n- NUNCA execute queries em tabelas tenant sem tenancy inicializado\n\n## Cashback System\n- Cashback SOMENTE \u00e9 creditado quando payment_status='paid'\n- NUNCA use status='completed' para gerar cashback\n- Auto-reverse cashback em cancelamentos/estornos\n- Cada restaurante configura % pr\u00f3prio (verificar cashback_settings)\n- Campos separados: cashback_used (desconto usado) \u2260 cashback_earned (ganho novo)\n\n## Pagamento (Asaas)\n- Split autom\u00e1tico (97% restaurante + 3% plataforma)\n- NUNCA duplique taxas (1 transa\u00e7\u00e3o = 1 split)\n- Webhook DEVE validar assinatura antes de processar\n- Sub-conta isolada por tenant (asaas_account_id)\n\n## Seguran\u00e7a\n- SEMPRE use prepared statements (Eloquent/Query Builder)\n- NUNCA concatene input do usu\u00e1rio em queries SQL\n- Valide TODOS os inputs (Request->validate())\n- Proteja contra XSS (escape outputs com {{ }} no Blade)\n- Mantenha CSRF tokens em formul\u00e1rios\n- LGPD: nunca exponha dados de clientes entre tenants\n\n## Padr\u00f5es Laravel 11\n- Use Service Layer para l\u00f3gica de neg\u00f3cio (AsaasService, CashbackService, OrderService)\n- Dependency Injection em controllers (NUNCA use new Class())\n- Observers para eventos autom\u00e1ticos (OrderObserver para cashback)\n- Jobs ass\u00edncronos para tarefas pesadas (emails, webhooks)\n- Valida\u00e7\u00e3o via Form Requests quando complexa\n\n## Middleware\n- NUNCA misture 'web' + 'api' no mesmo route group (causa SIGSEGV)\n- Rotas tenant SEMPRE com InitializeTenancyByDomain::class\n- API usa Sanctum + middleware 'web' (n\u00e3o 'api' em multi-tenant)\n\n## NFC-e / Fiscal\n- Emiss\u00e3o SOMENTE ap\u00f3s payment_status='paid'\n- Processo ass\u00edncrono via fila 'nfce' (n\u00e3o trava request)\n- Rate limiting: 10 NFC-e/min por tenant\n- Lock distribu\u00eddo previne duplica\u00e7\u00e3o\n- Classifica\u00e7\u00e3o fiscal: SELECT categorias (gr\u00e1tis) > Tributa AI (IA paga)\n\n## ANTES DE APLICAR FIX\n1. Verifique se mudan\u00e7a n\u00e3o quebra features funcionando\n2. Considere side effects em multi-tenant\n3. Valide regras de neg\u00f3cio (cashback, pagamento, fiscal)\n4. Teste mentalmente com dados reais\n5. Se n\u00e3o tiver 100% certeza, marque can_auto_fix=false\n\n## AUTO-FIX PERMITIDO\n\u2705 Use statements faltando\n\u2705 Typos em nomes de m\u00e9todos/propriedades\n\u2705 Par\u00e2metros faltando em fun\u00e7\u00f5es\n\u2705 Syntax errors (v\u00edrgula, par\u00eantese)\n\u2705 Type hints incorretos\n\n## REQUER REVIS\u00c3O MANUAL\n\u274c Queries que afetam m\u00faltiplos tenants\n\u274c L\u00f3gica de cashback/pagamento\n\u274c Emiss\u00e3o de nota fiscal\n\u274c Migrations ou schema changes\n\u274c Webhooks de pagamento\n\u274c Autentica\u00e7\u00e3o/autoriza\u00e7\u00e3o\n\u274c Qualquer mudan\u00e7a em dados financeiros\n\nSempre responda em JSON v\u00e1lido com esta estrutura:\n{\n  \"severity\": \"critical|high|medium|low\",\n  \"cause\": \"descri\u00e7\u00e3o clara da causa raiz\",\n  \"solution\": \"explica\u00e7\u00e3o da solu\u00e7\u00e3o proposta\",\n  \"code_fix\": \"c\u00f3digo corrigido completo (se aplic\u00e1vel)\",\n  \"file_path\": \"caminho exato do arquivo\",\n  \"can_auto_fix\": true|false,\n  \"security_impact\": \"nenhum|baixo|m\u00e9dio|alto\",\n  \"tests_needed\": [\"lista de testes que devem ser executados\"]\n}"
        }
      },
      "id": "claude-analyze",
      "name": "Claude - Analyze Error",
      "type": "n8n-nodes-base.anthropic",
      "typeVersion": 1,
      "position": [
        650,
        300
      ]
    },
    {
      "parameters": {
        "functionCode": "// Parse resposta do Claude\nconst claudeResponse = items[0].json.content[0].text;\n\n// Tenta extrair JSON da resposta\nlet analysis;\ntry {\n  // Remove markdown code blocks se houver\n  const jsonMatch = claudeResponse.match(/```json\\s*([\\s\\S]*?)```/) || \n                    claudeResponse.match(/\\{[\\s\\S]*\\}/);\n  \n  if (jsonMatch) {\n    analysis = JSON.parse(jsonMatch[1] || jsonMatch[0]);\n  } else {\n    analysis = JSON.parse(claudeResponse);\n  }\n} catch (e) {\n  // Se falhar, cria estrutura b\u00e1sica\n  analysis = {\n    severity: 'medium',\n    cause: 'N\u00e3o foi poss\u00edvel parsear resposta do Claude',\n    solution: claudeResponse,\n    can_auto_fix: false\n  };\n}\n\n// Adiciona dados do erro original\nanalysis.original_error = items[0].json.error;\n\nreturn {\n  json: analysis\n};"
      },
      "id": "parse-response",
      "name": "Parse Claude Response",
      "type": "n8n-nodes-base.function",
      "typeVersion": 1,
      "position": [
        850,
        300
      ]
    },
    {
      "parameters": {
        "functionCode": "// Valida\u00e7\u00e3o de seguran\u00e7a antes de aplicar auto-fix\nconst analysis = items[0].json;\n\n// Lista de arquivos BLOQUEADOS para auto-fix\nconst BLOCKED_FILES = [\n  '.env',\n  'composer.json',\n  'composer.lock',\n  'package.json',\n  'database/migrations/',\n  'config/database.php',\n  'app/Providers/AppServiceProvider.php',\n  'app/Providers/TenancyServiceProvider.php'\n];\n\n// Lista de padr\u00f5es PERIGOSOS no c\u00f3digo\nconst DANGEROUS_PATTERNS = [\n  /DB::raw\\(/i,\n  /DB::statement\\(/i,\n  /\\$_GET|\\$_POST|\\$_REQUEST/,\n  /exec\\(|system\\(|shell_exec\\(/,\n  /eval\\(/,\n  /DROP TABLE|TRUNCATE|DELETE FROM.*WHERE 1=1/i,\n  /->whereRaw\\(/,\n  /payment_status|cashback_balance|asaas_/i  // Campos financeiros\n];\n\n// Verifica se arquivo est\u00e1 bloqueado\nconst isBlockedFile = BLOCKED_FILES.some(blocked => \n  analysis.file_path?.includes(blocked)\n);\n\n// Verifica se c\u00f3digo cont\u00e9m padr\u00f5es perigosos\nconst hasDangerousPattern = analysis.code_fix \n  ? DANGEROUS_PATTERNS.some(pattern => pattern.test(analysis.code_fix))\n  : false;\n\n// Verifica impacto de seguran\u00e7a\nconst hasSecurityImpact = analysis.security_impact && \n  ['m\u00e9dio', 'alto', 'medium', 'high'].includes(analysis.security_impact.toLowerCase());\n\n// DECIS\u00c3O FINAL\nlet canAutoFix = analysis.can_auto_fix === true;\nlet blockReason = null;\n\nif (isBlockedFile) {\n  canAutoFix = false;\n  blockReason = 'Arquivo est\u00e1 na lista de bloqueio (cr\u00edtico para o sistema)';\n}\n\nif (hasDangerousPattern) {\n  canAutoFix = false;\n  blockReason = 'C\u00f3digo cont\u00e9m padr\u00f5es perigosos (raw SQL, exec, dados financeiros)';\n}\n\nif (hasSecurityImpact) {\n  canAutoFix = false;\n  blockReason = 'Impacto de seguran\u00e7a m\u00e9dio/alto - requer revis\u00e3o manual';\n}\n\n// Se severity for 'low', s\u00f3 aplica se Claude marcou explicitamente can_auto_fix=true\nif (analysis.severity === 'low' && !analysis.can_auto_fix) {\n  canAutoFix = false;\n  blockReason = 'Severidade baixa sem aprova\u00e7\u00e3o expl\u00edcita do Claude';\n}\n\nreturn {\n  json: {\n    ...analysis,\n    validated_auto_fix: canAutoFix,\n    block_reason: blockReason,\n    security_check: {\n      blocked_file: isBlockedFile,\n      dangerous_pattern: hasDangerousPattern,\n      security_impact: hasSecurityImpact\n    }\n  }\n};"
      },
      "id": "validate-security",
      "name": "Validate Security",
      "type": "n8n-nodes-base.function",
      "typeVersion": 1,
      "position": [
        1050,
        300
      ]
    },
    {
      "parameters": {
        "conditions": {
          "boolean": [
            {
              "value1": "={{ $json.validated_auto_fix }}",
              "value2": true
            }
          ]
        }
      },
      "id": "check-auto-fix",
      "name": "Can Auto-Fix?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 1,
      "position": [
        1250,
        300
      ]
    },
    {
      "parameters": {
        "authentication": "basicAuth",
        "url": "https://yumgo.com.br/api/auto-fix",
        "method": "POST",
        "jsonParameters": true,
        "bodyParametersJson": "={{ JSON.stringify($json) }}",
        "options": {
          "timeout": 30000
        }
      },
      "id": "apply-fix",
      "name": "Apply Auto-Fix",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 1,
      "position": [
        1250,
        200
      ]
    },
    {
      "parameters": {
        "content": "## \ud83d\udd34 ERRO DE PRODU\u00c7\u00c3O - YumGo\n\n**Severidade:** {{ $json.severity.toUpperCase() }}\n**Tenant:** {{ $json.original_error.tenant_name || 'Central' }}\n**URL:** {{ $json.original_error.url }}\n\n### Erro\n```\n{{ $json.original_error.exception }}: {{ $json.original_error.message }}\n{{ $json.original_error.file }}:{{ $json.original_error.line }}\n```\n\n### An\u00e1lise do Claude\n**Causa:** {{ $json.cause }}\n\n**Solu\u00e7\u00e3o:** {{ $json.solution }}\n\n**Impacto de Seguran\u00e7a:** {{ $json.security_impact || 'N\u00e3o avaliado' }}\n\n### C\u00f3digo Corrigido\n```php\n{{ $json.code_fix || 'N/A' }}\n```\n\n### Decis\u00e3o de Auto-Fix\n**Claude recomendou:** {{ $json.can_auto_fix ? '\u2705 SIM' : '\u274c N\u00c3O' }}\n**Valida\u00e7\u00e3o de Seguran\u00e7a:** {{ $json.validated_auto_fix ? '\u2705 APROVADO' : '\u274c BLOQUEADO' }}\n{{ $json.block_reason ? '**Motivo:** ' + $json.block_reason : '' }}\n\n**Status Final:** {{ $json.validated_auto_fix ? '\u2705 AUTO-FIX APLICADO' : '\u26a0\ufe0f REQUER REVIS\u00c3O MANUAL' }}",
        "channelName": "#production-errors",
        "attachments": []
      },
      "id": "notify-slack",
      "name": "Notify Slack",
      "type": "n8n-nodes-base.slack",
      "typeVersion": 1,
      "position": [
        1450,
        300
      ]
    },
    {
      "parameters": {
        "to": "seu-email@example.com",
        "subject": "\ud83d\udd34 [{{ $json.severity.toUpperCase() }}] Erro YumGo - {{ $json.original_error.exception }}",
        "emailType": "html",
        "html": "<h2>Erro de Produ\u00e7\u00e3o - YumGo</h2>\n<p><strong>Severidade:</strong> {{ $json.severity }}</p>\n<p><strong>Exce\u00e7\u00e3o:</strong> {{ $json.original_error.exception }}</p>\n<p><strong>Mensagem:</strong> {{ $json.original_error.message }}</p>\n<p><strong>Arquivo:</strong> {{ $json.original_error.file }}:{{ $json.original_error.line }}</p>\n<p><strong>URL:</strong> {{ $json.original_error.url }}</p>\n<p><strong>Tenant:</strong> {{ $json.original_error.tenant_name || 'Central' }}</p>\n\n<h3>An\u00e1lise do Claude</h3>\n<p><strong>Causa:</strong> {{ $json.cause }}</p>\n<p><strong>Solu\u00e7\u00e3o:</strong> {{ $json.solution }}</p>\n\n<h3>C\u00f3digo Sugerido</h3>\n<pre>{{ $json.code_fix || 'Requer an\u00e1lise manual' }}</pre>\n\n<p><strong>Auto-fix:</strong> {{ $json.can_auto_fix ? '\u2705 Aplicado automaticamente' : '\u274c Requer revis\u00e3o manual' }}</p>",
        "options": {}
      },
      "id": "notify-email",
      "name": "Notify Email (Critical Only)",
      "type": "n8n-nodes-base.emailSend",
      "typeVersion": 1,
      "position": [
        1250,
        400
      ]
    },
    {
      "parameters": {
        "functionCode": "// Cria commit autom\u00e1tico com a corre\u00e7\u00e3o\nconst fix = items[0].json;\n\nreturn {\n  json: {\n    message: `fix: ${fix.cause.substring(0, 72)}\\n\\n${fix.solution}\\n\\nAuto-fixed by Claude AI via n8n workflow\\nSeverity: ${fix.severity}\\n\\nCo-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>`,\n    files: [\n      {\n        path: fix.file_path,\n        content: fix.code_fix\n      }\n    ],\n    branch: `auto-fix/${Date.now()}`,\n    create_pr: fix.severity === 'critical'\n  }\n};"
      },
      "id": "prepare-commit",
      "name": "Prepare Git Commit",
      "type": "n8n-nodes-base.function",
      "typeVersion": 1,
      "position": [
        1250,
        100
      ]
    }
  ],
  "connections": {
    "Webhook - Flare Error": {
      "main": [
        [
          {
            "node": "Extract Error Data",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Extract Error Data": {
      "main": [
        [
          {
            "node": "Claude - Analyze Error",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Claude - Analyze Error": {
      "main": [
        [
          {
            "node": "Parse Claude Response",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Parse Claude Response": {
      "main": [
        [
          {
            "node": "Validate Security",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Validate Security": {
      "main": [
        [
          {
            "node": "Can Auto-Fix?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Can Auto-Fix?": {
      "main": [
        [
          {
            "node": "Apply Auto-Fix",
            "type": "main",
            "index": 0
          },
          {
            "node": "Prepare Git Commit",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Notify Email (Critical Only)",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Apply Auto-Fix": {
      "main": [
        [
          {
            "node": "Notify Slack",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Notify Email (Critical Only)": {
      "main": [
        [
          {
            "node": "Notify Slack",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "settings": {
    "executionOrder": "v1"
  },
  "staticData": null,
  "tags": [],
  "triggerCount": 1,
  "updatedAt": "2026-03-02T00:00:00.000Z",
  "versionId": "1"
}
Pro

For the full experience including quality scoring and batch install features for each workflow upgrade to Pro

About this workflow

Auto-Fix Production Errors with Claude. Uses anthropic, httpRequest, slack, emailSend. Webhook trigger; 10 nodes.

Source: https://github.com/orfeubr/yumgo-bridge/blob/f274d349b2da7140b2a36f74503a2bacdb517a76/n8n-workflows/auto-fix-errors.json — original creator credit. Request a take-down →

More AI & RAG workflows → · Browse all categories →

Related workflows

Workflows that share integrations, category, or trigger type with this one. All free to copy and import.

AI & RAG

Automatically detects missed Zoom demos booked via Calendly and triggers AI-powered follow-up sequences.

HTTP Request, OpenAI, Email Send +3
AI & RAG

Consulting firms in strategy, management, or IT who want to automate client onboarding and internal task assignment.

OpenAI, Google Sheets, Slack +3
AI & RAG

02 - Inbound Form AI Qualifier. Uses httpRequest, anthropic, hubspot, slack. Webhook trigger; 9 nodes.

HTTP Request, Anthropic, HubSpot +2
AI & RAG

10 - FAQ -> schema -> WP REST inject. Uses httpRequest, anthropic, slack. Webhook trigger; 8 nodes.

HTTP Request, Anthropic, Slack
AI & RAG

08 - YouTube transcript -> 9 assets. Uses httpRequest, anthropic, googleDocs, notion. Webhook trigger; 7 nodes.

HTTP Request, Anthropic, Google Docs +2