Failed Execution Diagnostic Tool for n8n

Summary

This sub-workflow provides a reusable diagnostic engine for analyzing failed n8n workflow executions. When called from another workflow, it inspects the execution result, identifies which nodes failed, classifies each error into a category (authentication, rate limit, timeout, network, invalid input, expression error, or general execution error), and produces a structured JSON output with the failure count, primary error category, recommended next steps, and sanitized error messages. This tool helps you quickly understand why a workflow failed and what to do next, without manually sifting through raw error logs.

Nodes

  • When Executed by Another Workflow (type: executeWorkflowTrigger) — No auth (internal trigger). This node acts as the entry point. It expects to be called via the "Execute Workflow" node from another workflow. It passes through the input data that contains the workflow definition and execution result to be analyzed.
  • Diagnose Failed Execution (type: code node) — No auth. This node contains a JavaScript function that processes the input. It extracts the node type map from workflow.nodes, analyzes execution.data.resultData.runData for errors, and classifies each error using keyword patterns. The output includes a diagnosticStatus, a list of failures with category, status code, message, and a recommendedNextStep, as well as aggregate counts and a primaryCategory.

Setup Instructions

No external accounts or service credentials are required. Import this workflow into your n8n instance. To use it, add an "Execute Workflow" node to any other workflow and point it to this sub-workflow. Pass the workflow and execution objects as input parameters (e.g., from a trigger or an error-handling path). Ensure the sub-workflow is saved and active (the trigger will only activate when called).

Use Cases & Variations

  • Automated Debugging: Integrate this diagnostic step into a main workflow's error handler (e.g., using the "Error Trigger" node) to automatically capture and analyze failures.
  • Monitoring & Alerting: Extend the output to send a summary to Slack, email, or a database by adding nodes after this sub-workflow.
  • Custom Classification: Modify the JavaScript code to adjust the error classification logic, add new categories, or change the recommended steps to match your team's runbooks.
  • Logging: Combine with a "Write to Google Sheets" or "Database" node to keep a historical record of failures over time.
2 nodesmanual triggerDevOps
Code

Workflow JSON

{
  "name": "n8n Failed Execution Doctor",
  "nodes": [
    {
      "parameters": {
        "inputSource": "passthrough"
      },
      "id": "df873507-97e1-4e2a-871a-b48fe4d72212",
      "name": "When Executed by Another Workflow",
      "type": "n8n-nodes-base.executeWorkflowTrigger",
      "typeVersion": 1.1,
      "position": [
        -260,
        0
      ]
    },
    {
      "parameters": {
        "jsCode": "const input = $input.first().json;\nconst workflow = input.workflow;\nconst execution = input.execution;\n\nif (!workflow || !Array.isArray(workflow.nodes)) {\n  throw new Error('workflow.nodes must be an array');\n}\nif (!execution || typeof execution !== 'object') {\n  throw new Error('execution must be an object');\n}\n\nconst nodeTypes = new Map(\n  workflow.nodes.map((node) => [String(node.name || ''), String(node.type || '')]),\n);\nconst data = execution.data && typeof execution.data === 'object' ? execution.data : {};\nconst result = data.resultData && typeof data.resultData === 'object'\n  ? data.resultData\n  : (execution.resultData && typeof execution.resultData === 'object' ? execution.resultData : {});\nconst lastNode = result.lastNodeExecuted ? String(result.lastNodeExecuted) : null;\nconst runData = result.runData && typeof result.runData === 'object' ? result.runData : {};\nconst failures = [];\nfunction safeMessage(value) {\n  let text = String(value ?? '').replace(/\\s+/g, ' ').trim();\n  text = text.replace(/(api[_-]?key|token|secret|password|authorization)\\s*[:=]\\s*[^\\s,;}]+/gi, '$1=[REDACTED]');\n  text = text.replace(/bearer\\s+[A-Za-z0-9._~+/-]{8,}/gi, 'Bearer [REDACTED]');\n  return text.slice(0, 300);\n}\n\nfunction classify(message, status) {\n  const text = `${String(status ?? '')} ${message}`.toLowerCase();\n  if (['401', '403', 'unauthorized', 'forbidden', 'credential', 'authentication'].some((x) => text.includes(x))) {\n    return ['authentication', 'Verify credential reference, auth scheme, token scope and expiry; then retest only the failing node.'];\n  }\n  if (['429', 'rate limit', 'too many requests'].some((x) => text.includes(x))) {\n    return ['rate_limit', 'Add bounded retry with exponential backoff and respect Retry-After or the upstream rate-limit policy.'];\n  }\n  if (['timeout', 'timed out', 'etimedout', 'econnaborted'].some((x) => text.includes(x))) {\n    return ['timeout', 'Set an explicit timeout, retry only idempotent work, and isolate the slow external call from the main path.'];\n  }\n  if (['econn', 'dns', 'network', 'connection refused', 'socket hang up'].some((x) => text.includes(x))) {\n    return ['network', 'Check endpoint reachability, DNS and TLS first; then add bounded retries and an explicit failure path.'];\n  }\n  if (['400', '422', 'invalid', 'validation', 'bad request'].some((x) => text.includes(x))) {\n    return ['invalid_input', 'Inspect the outbound payload/schema and validate required fields before the failing node.'];\n  }\n  if (['expression', 'undefined', 'cannot read', 'not defined', 'item linking'].some((x) => text.includes(x))) {\n    return ['expression', 'Validate referenced fields, item linking and optional values before evaluating the expression.'];\n  }\n  return ['execution_error', 'Reproduce the failing node with the same sanitized input, then add an explicit error path before re-enabling automation.'];\n}\n\nfunction addFailure(node, rawError) {\n  const error = rawError && typeof rawError === 'object' ? rawError : {};\n  const rawMessage = error.message || error.description || error.name || rawError || 'Execution failed';\n  const statusCode = error.httpCode ?? error.statusCode ?? error.status ?? null;\n  const message = safeMessage(rawMessage);\n  const [category, recommendedNextStep] = classify(message, statusCode);\n  failures.push({\n    node,\n    nodeType: node ? (nodeTypes.get(String(node)) || null) : null,\n    category,\n    statusCode,\n    message,\n    recommendedNextStep,\n  });\n}\nfor (const [nodeName, runs] of Object.entries(runData)) {\n  if (!Array.isArray(runs)) continue;\n  for (const run of runs) {\n    if (!run || typeof run !== 'object' || !run.error) continue;\n    addFailure(nodeName, run.error);\n  }\n}\nif (result.error && failures.length === 0) {\n  addFailure(lastNode, result.error);\n}\n\nconst counts = {};\nfor (const failure of failures) {\n  counts[failure.category] = (counts[failure.category] || 0) + 1;\n}\nconst primaryCategory = Object.entries(counts)\n  .sort((a, b) => b[1] - a[1])[0]?.[0] || 'unknown';\n\nreturn [{ json: {\n  workflowName: String(workflow.name || ''),\n  lastNodeExecuted: lastNode,\n  failureCount: failures.length,\n  primaryCategory,\n  failures,\n  diagnosticStatus: failures.length ? 'FAILED_EXECUTION_ANALYZED' : 'NO_STRUCTURED_ERROR_FOUND',\n  privacyNote: 'Common secret-like strings are redacted and error messages are truncated.',\n} }];\n"
      },
      "id": "4aa207b4-a12c-482e-8313-32ad43dd7680",
      "name": "Diagnose Failed Execution",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        0,
        0
      ]
    }
  ],
  "pinData": {},
  "connections": {
    "When Executed by Another Workflow": {
      "main": [
        [
          {
            "node": "Diagnose Failed Execution",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "active": false,
  "settings": {
    "executionOrder": "v1"
  },
  "id": "44b9dc86-702b-45e8-9b71-803799778a26",
  "versionId": "ca9abd80-9bb7-4c14-83e5-00c53828ada5"
// ... truncated (copy to see full JSON)

How to Import This Workflow

  1. 1Copy the workflow JSON above using the Copy Workflow JSON button.
  2. 2Open your n8n instance and go to Workflows.
  3. 3Click Import from JSON and paste the copied workflow.

Don't have an n8n instance? Start your free trial at n8nautomation.cloud

Related Templates

Automated n8n Workflow Backup to GitHub Repository

Overview This workflow automatically backs up every workflow in your n8n instance to a dedicated GitHub repository. It runs on a configurable schedule (or manually) and ensures that all your workflow JSON files are version-controlled and safely stored in a structured folder. The backup process intelligently handles both new workflows (creates a file) and existing ones (updates the file), making it ideal for disaster recovery, collaboration, or tracking changes over time. Step-by-Step Node Breakdown Schedule Trigger (No additional auth) — Triggers the workflow on a recurring interval. By default it runs hourly, but you can customize the schedule (e.g., daily at midnight) to suit your needs. Also supports manual execution via the Manual Trigger node. Manual Trigger (No auth) — Provides a manual button to run the backup immediately, useful for testing or on-demand backups. Get many workflows (Internal n8n API, no external credentials) — Fetches a list of all workflows from your n8n instance using the built-in n8n node. No separate API key is required; it uses the same authentication as your n8n session. Loop Over Items (No auth) — Iterates over each workflow in the list one at a time. This node processes workflows sequentially, preventing race conditions. Getafile (GitHub, OAuth2 / Personal Access Token) — Attempts to retrieve the existing workflow file from your GitHub repository at the path . If the file does not exist (i.e., a new workflow), the node’s error output is triggered. The expression in sanitizes the workflow name by replacing invalid characters (), converting to , and normalizing spaces. Convert to File1 (No auth) — Converts the retrieved GitHub file’s binary data back to a JSON object so it can be compared or overwritten. Extract from File1 (No auth) — Extracts the JSON content from the binary file, preparing it for an update operation. Edit a file (GitHub, OAuth2 / Personal Access Token) — If the workflow already exists on GitHub, this node updates the file with the latest JSON from your n8n instance. The commit message is dynamically generated (e.g., ). Convert to File (No auth) — Converts the current n8n workflow JSON into a binary file () with the workflow’s name as the filename. Create a file (GitHub, OAuth2 / Personal Access Token) — If the workflow is new (i.e., error output), this node creates a new file in the folder. The commit message includes the workflow name and . The workflow loops back to the Loop Over Items node to process the next workflow. The Sticky Note at the top serves as a comment. Setup Instructions GitHub account — You need a GitHub account and a repository (e.g., ) to store the backups. Create an empty repository or use an existing one. GitHub credential in n8n — Add a GitHub OAuth2 or Personal Access Token credential in n8n under Credentials > GitHub. Ensure the token has scope (or at least and ). Configure the nodes — - In Get many workflows, no changes needed. - In Getafile, Create a file, and Edit a file, update the and fields to match your GitHub username and repo name. - Optionally adjust the Schedule Trigger interval (set hours/minutes as desired). Error handling — The workflow references an external error workflow (). If you don’t have that, you should either create a simple error handler or remove the setting in the workflow settings. Use Cases & Adaptations Disaster recovery — Restore all workflows by downloading the JSON files from GitHub and importing them back into n8n. Version history — Track changes to workflows over time via GitHub commits and diffs. Multi-instance sync — Modify the workflow to run on multiple n8n instances, pushing to the same repo (be cautious with conflicts). Selective backup — Add a filter node after to only backup workflows with a specific tag or name pattern. Notification — Insert a Slack or email node after the loop to notify you when a backup completes or if an error occurs.

11 nodes

n8n Upgrade: Detect Affected Workflows with Broken Connections

Summary This workflow helps n8n administrators identify workflows that may have been affected by a past upgrade (specifically n8n version ) where multi-output nodes (like , , ) could have their output connections accidentally re-wired. It provides a self-service webhook endpoint that returns an HTML report listing all workflows with potentially broken connections, making it easy to audit and fix them. Node-by-Node Walkthrough Webhook (No auth) — Listens for HTTP GET requests at the path . When a user visits this URL in their browser, the workflow is triggered. The response mode is set to "Response Node", meaning the final output will be sent back directly. Get all workflows (API Key auth) — Uses the n8n API to fetch all workflows from the instance. You must configure this node with an n8n API credential (a personal access token created under Settings > n8n API). The node has no filters, so it retrieves every workflow. Parse potentially affected workflows (Code node, no auth) — A JavaScript code node that loops through each workflow, inspects its connections, and checks if any multi-output node (defined in the array) has empty outputs. If a node has fewer connected outputs than expected, it is flagged as potentially affected. The node outputs a JSON object with an array of affected workflows, each containing , , , and . Generate Report (HTML node, no auth) — Creates a static HTML document with a styled container, a heading, and an empty list. This serves as the shell for the interactive report generated by the next node. Serve HTML Report (Respond to Webhook node, no auth) — Takes the HTML template from the previous node and injects JavaScript that parses the affected workflows data (from the code node) and dynamically builds a list of clickable links. Each link opens the workflow in a new tab so the admin can inspect and fix the connections. The response headers are set to . Setup Instructions Prerequisites: You must have admin access to the n8n instance (the workflow must be run by the instance owner). Create an n8n API key: Go to Settings > n8n API in your n8n instance and generate a personal access token. Copy the token. Configure the "Get all workflows" node: Add an n8n credential of type "API Key" and paste the token. Leave the filters empty. Customize multi-output nodes (if needed): The code node contains a list with the default nodes (, , ). If you have community nodes with multiple outputs, add them to this array with their correct output count. Activate the workflow: Toggle the workflow to active. Use the report: Open your browser and navigate to . The page will list all affected workflows. Click on a row to open the workflow in a new tab — inspect the connections and re-wire them if needed. Use Cases & Variations Post-upgrade audit: Run this workflow after every n8n upgrade to catch connection issues early. Customized detection: Extend the array in the code node to include any custom node type that has multiple outputs. Slack/Email notification: Instead of serving an HTML report, you could send the list of affected workflows to a Slack channel or email using additional nodes. Scheduled scanning: Replace the Webhook trigger with a Schedule trigger to run the check daily and automatically notify the admin.

9 nodes

Manual Trigger with Error Handler - Production Template

Overview This is a foundational n8n workflow template designed to demonstrate a robust, production-ready pattern for manual workflow execution with integrated error handling. It provides a clean starting point for building more complex automations by establishing best practices for error management and workflow structure from the outset. The workflow is intentionally minimal but includes critical production features: a manual trigger for on-demand execution, a dedicated error handler node that gracefully stops execution on failure, and comprehensive workflow settings configured for reliability (retry logic, timeout limits, and execution tracking). This makes it ideal for users who want to learn n8n's error handling capabilities or need a reliable skeleton for mission-critical automations. Workflow Steps Manual Trigger (No auth) — This is the starting point of the workflow. It allows you to run the workflow manually by clicking the "Execute Workflow" button in the n8n editor. No authentication is required for this trigger node itself. The node has no additional parameters configured, meaning it simply fires when manually activated. Error Handler (No auth) — Connected as an error workflow handler (though in this JSON it is not wired via connections, it is placed as a standalone error-catching node). This node uses the "Stop and Error" type, which means if any error occurs during workflow execution, this node will catch it and stop the workflow with a custom error message: "Workflow execution error". The parameter is empty, so no additional error handling behavior (like sending notifications) is configured. No authentication is required. Setup Instructions No external accounts required — This workflow uses only built-in n8n nodes (Manual Trigger and Stop & Error). You do not need any third-party service accounts or API keys. Import the workflow — Copy the JSON and paste it into your n8n instance via "Workflows > Add Workflow > Import from JSON". Customize the error message — If desired, edit the Error Handler node's "Message" parameter to provide a more specific error description relevant to your use case. Add your logic — Connect additional nodes after the Manual Trigger to perform your actual automation tasks. The Error Handler will automatically catch any errors from those nodes. Configure workflow settings — Review the existing settings (retry on fail, timeout, etc.) and adjust them to match your production requirements. Use Cases and Variations Learning template — Use this as a teaching tool to understand how error handling works in n8n workflows. Production skeleton — Start every new automation by duplicating this workflow, then add your business logic nodes between the trigger and error handler. Error notification system — Extend the Error Handler by adding a Slack, email, or webhook node after it to send alerts when errors occur. Multi-trigger adaptation — Replace the Manual Trigger with a Schedule Trigger, Webhook Trigger, or Event Trigger to make the workflow run automatically. Conditional error handling — Add an IF node before the Error Handler to route different error types to different handling logic (e.g., retry vs. notify vs. log).

2 nodes

Ready to automate with n8n?

Get affordable managed n8n hosting with 24/7 support.