n8n error handling official
Use when building any webhook-triggered workflow, scheduled/production-bound workflow, wiring a per-node error output, or any workflow where silent failure would drop user-visible work. Triggers on "webhook", "respond to webhook", "API", "production", "error", "failure", "5xx", "try/catch", "error workflow", "onError", "continueErrorOutput", "error branch", "node error output", "output(1)", "main[1]", "scheduled", or any workflow that runs unattended.
By- name:
- n8n-error-handling-official
- description:
- Use when building any webhook-triggered workflow, scheduled/production-bound workflow, wiring a per-node error output, or any workflow where silent failure would drop user-visible work. Triggers on "webhook", "respond to webhook", "API", "production", "error", "failure", "5xx", "try/catch", "error workflow", "onError", "continueErrorOutput", "error branch", "node error output", "output(1)", "main[1]", "scheduled", or any workflow that runs unattended.
n8n Error Handling
Default n8n node behavior: error → workflow halts → caller gets nothing useful. For unattended workflows (webhook APIs, scheduled jobs, queue workers), that default is wrong. The symptom is "the integration just stopped working" with no log, no message, no clue.
This skill is about handling errors so failures are loud, structured, and recoverable. Or best case scenario, handled in a way where it self heals.
Non-negotiables
For any API-shaped workflow (webhook trigger paired with Respond to Webhook):
- Every fallible node's error output is wired, and both paths end at a
Respond to Webhook. No hanging error branches, or the caller would see a timeout. "Fallible" = HTTP, DB, third-party API, file operation, anything that throws. - Status code maps to cause. Caller's fault → 4xx, your fault → 5xx. A 200 default on an error path produces silent failure: caller thinks success, processes empty data.
For any unattended workflow (scheduled, cron, queue-driven, agent tool):
3. Set a workflow-level error workflow. Catches what escapes per-node handling: timeouts, crashes between nodes, errors in unwired nodes. Set it via update_workflow setWorkflowSettings.errorWorkflow (n8n 2.29.0+); the target must be a published workflow containing an active Error Trigger, or the update is rejected. See references/ERROR_WORKFLOWS.md.
Strong defaults
- Error response bodies are structured. Not just "Internal Server Error". Use
{ "error": "<short identifier>", "message": "<human-readable>" }. Seereferences/RESPONSE_SHAPES.md. - Network-calling nodes have
retryOnFailconfigured. Transient 429s and upstream blips get absorbed before reaching the error path. See "Self-healing on transient failures" below.
When error handling can be looser
Internal one-off workflows where you're the only user, you watch each run, and the cost of failure is "I notice and re-run". Default onError: 'stopWorkflow' is fine. The line: if anyone other than you sees the output (downstream system, end user, on-call), the non-negotiables apply.
API workflow shape
The canonical webhook-API workflow:
Webhook trigger
├── (success path) → Process → Respond to Webhook (200, body)
└── (any node's error output)
→ Respond to Webhook (5xx, structured error body)
→ Optional: log to error tracker / logger / notify channel
For a complete walkthrough including how to wire multiple fallible nodes to a single error responder, see references/API_WORKFLOWS.md.
Schema validator (Set IIFE)
For any webhook API doing input validation, lift the Set-based schema validator pattern into the endpoint instead of writing IF/Switch chains per field. The two example files are the source of truth:
references/examples/validation-subworkflow.ts: the bare pattern (Webhook → Set with the validation IIFE → Respond, expression-driven status code). Useful as a minimal demo.references/examples/validation-subworkflow-usage.ts: the endpoint pattern (Webhook → Set → If valid → your business logic → 200 success / 400 with the standard{error: "validation_error", message, details, request_schema}body). Lift this into your endpoint and replace the NoOp placeholder with real logic.
The procedure for an agent using this:
- Lift the usage-example structure into the new endpoint. Webhook → Set (Validate Schema) → If Params Valid → your logic → success/400 Respond. Don't reinvent.
- Edit the IIFE for your schema. Update
REQUIRED_SCHEMAand the per-field checks inside the Set node's expression for your endpoint's input shape. The pattern below the schema constant is mechanical: presence check, type check, constraint check, push toerrors[]. - Leave the output shape alone.
valid,validationError,details,requiredSchemaare the contract the Respond node consumes. Renaming them breaks the response body.
The full procedure, supported constraint patterns, schema design rules, and the ={{ ... }} wrapping gotchas live in references/API_WORKFLOWS.md "Schema validator (Set IIFE)".
Per-node error setup (recap)
Each fallible node needs two changes (see references/NODE_ERROR_OUTPUTS.md):
- Set
onError: 'continueErrorOutput'on the node config. - Wire
output(1)to your error handler.
Both required. One without the other is the silent-failure mode.
Self-healing on transient failures
Before wiring the error path, configure node-level retry on any node making a network call (HTTP Request, comms like Gmail/Slack/Discord, DB, AI, third-party API nodes). Transient 429s and brief upstream blips get absorbed, so the error output then only fires on real failures, and alerts and 5xx responses reflect actual problems instead of noise.
{
retryOnFail: true,
maxTries: 3,
waitBetweenTries: 5000, // ms; 5000 is the max and should be your default
}
Works on any node that calls a network service, not just HTTP Request. The engine retries on any error, with no per-status-code filter, and the engine caps maxTries at 5 and waitBetweenTries at 5000ms (packages/core/src/execution-engine/workflow-execute.ts). See n8n-node-configuration-official HTTP_NODES.md and AI_NODES.md for node-specific notes.
Response shapes: map the cause to the status code
A 5xx response with text/plain "Internal Server Error" is technically 5xx but useless. And not every error is 5xx. Match the status code to why the request failed.
Common mistake: wiring every error path to a single Respond to Webhook returning 500 "internal_error". Every failure looks the same to the caller, even when they sent bad input. Breaks monitoring: you can't distinguish real outages from bad caller input.
Default mapping by cause:
| Cause | Status | Error code | Path |
|---|---|---|---|
| Required field missing or wrong type | 400 | validation_error |
Validate up front with the Set-based schema validator (see references/examples/validation-subworkflow.ts for the bare pattern and validation-subworkflow-usage.ts for the endpoint template), or, for trivial cases, an inline IF/Switch + dedicated 400 Respond. Don't go through error outputs. Ideally echo the schema in the response so the caller can self-correct. |
| Auth missing or invalid | 401 | unauthorized |
Same. Check up front, return 401 directly. |
| Authenticated but not allowed | 403 | forbidden |
Same. |
| Resource ID exists in request, doesn't in your data | 404 | not_found |
Branch off the lookup result, not the lookup error. |
| Operation conflicts with current state (duplicate, race) | 409 | conflict |
Detect with logic, not error output. |
| Caller exceeded rate limit | 429 | rate_limit_exceeded |
Set Retry-After header. |
| Node threw and you don't know why | 500 | internal_error |
The error-output path. |
| Third-party API errored | 502 | upstream_error |
Error output of the HTTP Request node. |
| Workflow can't currently process (downstream down, rate-limited upstream) | 503 | service_unavailable |
Detect via specific error, return with hint. |
| Third-party API timed out | 504 | upstream_timeout |
Error output filtered by error message. |
Two distinct flows:
- Validation failures (4xx) are checked upstream of the work, via IF/Switch branches, not error outputs. Use a dedicated Respond per shape (400 missing field, 401 no auth, etc.).
- Execution failures (5xx) come out of error outputs ("we tried, something broke"). A single error responder for all 5xx is fine. Differentiate the body's
errorcode by inspecting the failed node where useful.
One Respond, expression-driven status code. When the error path differs only by status code and message text (same body shape, no header/content-type changes), don't fan out to N Respond nodes via a Switch. The Respond to Webhook node accepts expressions in its Response Code and body fields. Compute the code inline, so one Respond node carries the whole error path.
// Response Code on a single Respond to Webhook node:
{{ (() => {
const msg = $json.error?.message || $json.message || ''
if (msg.includes('INVALID_ID')) return 400
if (/429|too many/i.test(msg)) return 429
if (/openrouter|anthropic|llm/i.test(msg)) return 502
return 500
})() }}
Switch + N Responds only earn their place when responses diverge structurally: different headers, different body shapes, redirects, different content types. Same shape with a different number is one expression-driven Respond.
For full conventions including correlation IDs, retryable-vs-fatal flags, validation details, and rate-limit shapes, see references/RESPONSE_SHAPES.md.
Workflow-level error workflows
For unattended workflows, configure the instance's error workflow (or per-workflow override) to point at a workflow that:
- Captures the failure (workflow name, execution ID, error, stack).
- Notifies someone (Slack, email, on-call).
- Optionally enqueues a retry (with backoff).
Catches what per-node handling misses: timeouts, crashes between nodes, errors in unwired nodes.
See references/ERROR_WORKFLOWS.md.
Reference files
| File | Read when |
|---|---|
references/API_WORKFLOWS.md |
Building or reviewing a webhook-trigger / respond-to-webhook workflow |
references/ERROR_WORKFLOWS.md |
Setting up workflow-level error catching for production workflows |
references/RESPONSE_SHAPES.md |
Defining the response body conventions for your APIs |
references/NODE_ERROR_OUTPUTS.md |
Wiring a per-node error output on individual fallible nodes |
Anti-patterns
| Anti-pattern | What goes wrong | Fix |
|---|---|---|
| Webhook → process → respond, no error branch | Caller gets timeout or empty 500 | Wire every fallible node's output(1) to a Respond to Webhook |
| Single Respond to Webhook for both paths | Body shape doesn't tell caller what happened | Two Respond nodes, one per path, with explicit codes and bodies |
Error path returns 200 with { "error": ... } body |
Caller's HTTP client treats it as success, so error handling never fires | Always 4xx/5xx for error paths |
| Catching errors in Code node and returning them as data | Downstream sees error-shaped data, workflow continues | Let it throw, configure onError: 'continueErrorOutput' and wire the error path |
| Production workflow with no workflow-level error workflow | A genuine failure goes nowhere | Set up an error workflow. See ERROR_WORKFLOWS.md |
| Generic "Internal Server Error" on every failure | Can't distinguish caller bug from upstream from rate limit | Structured error codes. See RESPONSE_SHAPES.md |
Production node calls a flaky or rate-limited API with no retryOnFail |
Every transient 429 or upstream blip surfaces as a 5xx, and alerts fire on noise | Set retryOnFail: true, maxTries: 3, waitBetweenTries: 5000 on the node. See "Self-healing on transient failures" |
| 500 for everything not a 200 | Caller can't separate their bad input from your outage, so their monitoring fires on your noise | Map cause → status code. Caller issues are 4xx. |
| Switch over the error message → N Respond nodes that differ only by status code | 5 nodes for what's one Respond with an expression-driven Response Code |
Compute the code inline in a single Respond. See "One Respond, expression-driven status code" above. |
Open this reference as its own page
API workflows
The canonical n8n pattern for "this workflow is an HTTP API":
Webhook trigger → [processing] → Respond to Webhook
This file covers wiring that pattern with proper error handling so the API behaves under failure, not just happy-path.
The shape
A production webhook API:
┌─→ Validate input ─→ ... ─→ Respond (200, success body)
Webhook trigger ───────┤
└─→ (any error output)
→ Respond (5xx, structured error body)
→ (optional) Log / notify
Variants:
- Multiple processing branches: each eventually flows to either success or error Respond.
- Long-running work: webhook responds 202 immediately, work continues async. See end of file.
Wiring every fallible node
For each fallible node (HTTP, DB, third-party, validation):
- Set
onError: 'continueErrorOutput'in the node config. - Wire
output(1)to your error Respond node, possibly via a logger or normalizer.
Concretely:
const fetchUser = node({
type: 'n8n-nodes-base.postgres',
config: {
parameters: { /* ...query config... */ },
onError: 'continueErrorOutput',
},
})
const callExternal = node({
type: 'n8n-nodes-base.httpRequest',
config: {
parameters: { /* ...config... */ },
onError: 'continueErrorOutput',
},
})
const respondError = node({
type: 'n8n-nodes-base.respondToWebhook',
config: {
parameters: {
responseCode: 502,
responseBody: '={{ JSON.stringify({ error: "upstream_error", message: $json.error?.message ?? "External service failed" }) }}',
options: { responseHeaders: { entries: [{ name: 'Content-Type', value: 'application/json' }] } },
},
},
})
workflow
.add(webhook.output(0).to(fetchUser))
.add(fetchUser.output(0).to(callExternal))
.add(callExternal.output(0).to(respondSuccess))
// Error paths: both go to the same responder
.add(fetchUser.output(1).to(respondError))
.add(callExternal.output(1).to(respondError))
Three things to notice:
- One
respondErrorfor many sources. Fan-in keeps the workflow readable. - Both fallible nodes have
onError: 'continueErrorOutput'. If either is missing, that node's failure halts the workflow instead of routing. - The error body uses an expression to surface the actual error message. Be careful what you leak. See "Don't leak internals" below.
What "fallible" means
A node is fallible if any of these can happen:
- Network call (HTTP, third-party API, DB).
- Auth failure (credential expired, token rotated).
- Schema mismatch (DB column missing, JSON parse failure).
- Rate limit (429 from upstream).
- Logic error (Code node throws).
- File operation (missing path, permissions).
Nodes not typically fallible:
- Set / Edit Fields on pure data (can still fail on bad input, so validate upstream).
- IF / Switch with simple expressions (if it throws, it's a bug, not something to catch).
- Function nodes without I/O (pure transformations).
When in doubt, wire error handling. The cost is one extra connection.
The "Validate input" stage: where most 4xx responses live
Validate webhook input before processing. Fail fast with 4xx, don't lump caller-side errors with real outages.
Validation failures go through IF/Switch + dedicated Respond, not error outputs. They're expected failures with a known response, not node failures.
const validate = ifElse({
config: {
parameters: {
conditions: { /* check required fields */ },
},
},
})
const respondBadRequest = node({
type: 'n8n-nodes-base.respondToWebhook',
config: {
parameters: {
responseCode: 400,
responseBody: '={{ JSON.stringify({ error: "validation_error", message: "Missing required field: customer_id" }) }}',
},
},
})
workflow
.add(webhook.output(0).to(validate))
.add(validate.onTrue(processing)) // valid → process
.add(validate.onFalse(respondBadRequest)) // invalid → 400
Schema validator (Set IIFE)
For any webhook needing structured input validation, lift the Set-based validator pattern, not a hand-rolled IF chain. Two example files are the source of truth:
examples/validation-subworkflow.ts: the bare pattern (Webhook → Set → expression-driven Respond). Useful as a minimal reference.examples/validation-subworkflow-usage.ts: the endpoint pattern (Webhook → Set → If valid → your business logic → 200 success / 400 with structured body). Lift this into any new endpoint.
The procedure for using these:
- Lift the usage-example structure into your endpoint. The node graph (Webhook → Validate Schema → If Params Valid → your logic → success/400 Respond) is already the right shape. Replace the
Your workflow logic hereNoOp with your real processing. - Edit
REQUIRED_SCHEMAand the per-field checks inside the IIFE. The Set node'sresultassignment holds an inline IIFE. TheREQUIRED_SCHEMAconstant at the top is for echo-back; the actual checks live in the per-fieldif/else ifblock below it. Add, remove, or change checks to match your endpoint's input shape. - Don't change the output keys. The IIFE returns
{ valid, validationError, details, requiredSchema }. The Respond nodes consume those names. Renaming any of them breaks the response body.
The 400 body shape ({ error: "validation_error", message, details, request_schema }) matches the default in RESPONSE_SHAPES.md. Don't deviate.
Output contract. The Set node's result field (an object) is what downstream nodes branch on:
- Valid:
{ valid: true, validationError: null } - Invalid:
{ valid: false, validationError: <human-readable summary string>, details: { <path>: <message>, ... }, requiredSchema: <the schema, echoed back> }
The usage example maps these into the standard 400 body: validationError becomes message, details is forwarded as-is, and requiredSchema becomes request_schema. The schema is echoed back so the caller (or an LLM) can self-correct.
Supported constraint patterns. The hand-crafted IIFE covers the same subset of JSON Schema constraints as a generic validator, applied to your specific schema:
| Category | What to write inline |
|---|---|
| Required field present | if (!("name" in body)) errors.push(...) |
| Type check | else if (typeof body.name !== "string") errors.push(...) |
| String constraints | body.name.length < N, /regex/.test(body.email) |
| Number constraints | body.seat_count < min, > max, Math.floor(v) !== v for integer |
| Enum | ["a","b","c"].indexOf(body.plan) === -1 |
| Array | Array.isArray(body.tags), body.tags.length < N |
| Conditional | nest the checks inside if (body.type === "X") { ... } |
Schema design rules (REQUIRED_SCHEMA constant is what gets echoed back to the caller):
- Every field SHOULD have a
descriptionin plain language. The IIFE appends them to error lines (• name: Missing required field "name" - Customer full name). - Use
integertype (with theMath.floor(v) !== vcheck) for whole numbers. - Use a literal array for enums and
.indexOf(...) === -1to check. - Use
additionalProperties: falsesemantically (echoed back) and add an explicit "Unknown field" check in the IIFE if you want to reject extras at runtime.
Embedding gotcha: regex backslashes in the REQUIRED_SCHEMA literal. Inside the SDK's TS template literal, regex \S written as a JS string needs four backslashes:
email: { type: "string", pattern: "^\\\\S+@\\\\S+\\\\.\\\\S+$", description: "Contact email" }
The chain: TS template literal \\\\ → string \\ → JS string \\ (escape) → runtime char \. The regex literal in the IIFE itself uses the simpler form /^\\S+@\\S+\\.\\S+$/ (two backslashes per \S in TS source).
Example error output. Given a schema requiring name, email, plan, seat_count, and a non-empty tags array, a malformed payload produces:
Validation failed (5 issues):
• name: Missing required field "name" - Customer full name
• email: "not-an-email" is not valid - Contact email address
• plan: "premium" is not an allowed value. Must be one of: starter, pro, enterprise - Subscription plan
• seat_count: Expected type "integer" but got "non-integer number" - Number of licensed seats
• tags: Must have at least 1 item(s), got 0 - At least one tag for categorization
The description from each field is pulled into the message, so callers and downstream LLMs get actionable hints, not just a "validation failed" opaque string.
Real APIs need more than one 4xx path. Common ones to wire before processing:
Webhook trigger
→ Auth check (header present + valid?)
├── No → Respond 401 unauthorized
└── Yes ↓
→ Validate input (required fields, types, value ranges)
├── Invalid → Respond 400 validation_error (with `details` per field)
└── Valid ↓
→ Authorization check (does this caller's auth allow this operation?)
├── Not allowed → Respond 403 forbidden
└── Allowed ↓
→ Lookup target resource
├── Doesn't exist → Respond 404 not_found
└── Exists ↓
→ Processing stage (HTTP calls, DB writes, etc.). This is where 5xx errors come from
Each upstream check is a separate IF/Switch + Respond pair. That's not over-engineering. It gives the caller a useful error code instead of a generic 500.
5xx error responses: the execution-failure path
Past validation, remaining errors are 5xx: nodes failing, upstream timing out, etc. Wire via per-node error outputs.
A single error responder for all 5xx is fine, but differentiate the body by inspecting which failure happened:
const respondError = node({
type: 'n8n-nodes-base.respondToWebhook',
config: {
parameters: {
responseBody: `={{ (() => {
const err = $json.error ?? {}
const node = err.node?.name ?? 'unknown'
// Distinguish by failed node or error message
if (err.message?.includes('timeout')) {
return JSON.stringify({ error: 'upstream_timeout', message: 'External service did not respond in time' })
}
if (err.message?.includes('rate limit')) {
return JSON.stringify({ error: 'service_unavailable', message: 'Rate limit hit on upstream service' })
}
return JSON.stringify({ error: 'internal_error', message: 'An internal error occurred' })
})() }}`,
options: {
responseCode: `={{ $json.error?.message?.includes('timeout') ? 504 : ($json.error?.message?.includes('rate limit') ? 503 : 500) }}`,
responseHeaders: { entries: [{ name: 'Content-Type', value: 'application/json' }] },
},
},
},
})
Don't leak internals in error responses
Tempting:
responseBody: '={{ JSON.stringify({ error: "internal_error", details: $json.error }) }}',
What $json.error actually contains: stack traces, internal node names, sometimes connection strings, sometimes upstream responses with embedded secrets.
Better: log the full error privately, return a sanitized message:
const respondError = node({
type: 'n8n-nodes-base.respondToWebhook',
config: {
parameters: {
responseCode: 502,
responseBody: '={{ JSON.stringify({ error: "upstream_error", message: "External service failed" }) }}',
},
},
})
// Separately, log full details
const logError = node({
type: 'n8n-nodes-base.httpRequest',
config: {
parameters: { /* ...send full error to your logging service / Sentry / Slack... */ },
},
})
.add(callExternal.output(1).to(logError))
.add(logError.output(0).to(respondError))
The caller sees a clean message. Internal details stay internal. If you operate distributed tracing and want a correlation ID in the body, add request_id per the "When to add request IDs" section in RESPONSE_SHAPES.md (and add it consistently across success and error responses on every endpoint, not just here).
Correlation IDs (optional, opt-in)
The default response shape doesn't include a request_id, see "When to add request IDs" in RESPONSE_SHAPES.md for when it's worth adding. If you do opt in (you're running distributed tracing or log correlation), two ways to source the ID:
- Caller-supplied: check
X-Request-IDheader, pass through and include in responses. - Generated: use
$execution.idor generate a UUID, include in responses and logs.
Either works. Generated is easier, caller-supplied is better for distributed tracing. Do it on every endpoint or none, partial coverage is worse than no coverage.
Status code conventions
The status code is the caller's first signal. Be deliberate:
- 2xx: success. 200 sync, 202 "accepted, processing".
- 4xx: caller's fault. 400 (bad input), 401 (no auth), 403 (not allowed), 404 (not found), 429 (rate limited).
- 5xx: your fault. 500 (unexpected internal), 502 (upstream broken), 503 (temporarily down), 504 (upstream timeout).
Distinguishing 4xx from 5xx matters because:
- Caller monitoring alerts on 5xx (your fault) but not 4xx (their fault).
- 5xx suggests retry, 4xx suggests don't.
- Aggregated error rates segment by class.
Async / 202-Accepted pattern
If the work takes longer than the caller wants to wait:
Webhook trigger
→ Validate input
→ Respond to Webhook (202, { "job_id": "..." }) ← respond immediately
→ Continue processing in same workflow OR Execute Workflow (sub-workflow)
→ On completion: callback / queue / email
The webhook returns 202 with a job_id (the identifier the caller will use to poll status), and processing continues async. The caller polls a status endpoint or receives a callback to a webhook they provided. The job_id is intrinsic to the async pattern (it's how you find the work later), not the optional request_id correlation field discussed above.
Its own pattern with its own gotchas (idempotency, callback retries, status tracking). Build deliberately.
Verifying the API workflow
Before publishing:
- Test the success path with
test_workflow. Confirm shape and code. API workflows almost always have side-effecty downstreams (DB writes, third-party calls, comms), so ask the user before testing. Seen8n-workflow-lifecycle-officialreferences/TESTING.md. - Trigger an error path. Use
prepare_workflow_pin_datato inject a value that breaks a processing node, thentest_workflow. Confirm the error Respond fires with the right code/body. - Verify connections via
get_workflow_details. Every fallible node hasonError: 'continueErrorOutput'ANDoutput(1)wired. Seereferences/NODE_ERROR_OUTPUTS.md. - Confirm no internal details leak in the error body.
If any are off, fix before publish.
Open this reference as its own page
Workflow-level error workflows
Per-node error outputs handle one node's failure. They don't catch:
- Failures in nodes you forgot to wire.
- Crashes between nodes.
- Workflow timeouts.
- Issues with the trigger itself.
For unattended workflows, this gap matters: silent failure means no alert, no log, no clue. The fix is a workflow-level error workflow: when an unhandled error escapes, n8n invokes the designated error workflow with the failure context.
What an error workflow looks like
Triggered by the Error Trigger node. Receives roughly this shape (verified against IWorkflowErrorData in packages/cli/src/interfaces.ts and ExecutionBaseError.toJSON in packages/workflow/src/errors/abstract/execution-base.error.ts):
{
"execution": {
"id": "...",
"url": "...",
"retryOf": "...",
"error": {
"name": "NodeApiError",
"message": "...",
"description": "...",
"context": { },
"timestamp": 1715000000000
},
"lastNodeExecuted": "Fetch order",
"mode": "trigger"
},
"workflow": {
"id": "...",
"name": "Sync Stripe customers"
}
}
The error workflow's job:
- Identify the failure and surface it (Slack/email/PagerDuty).
- Optionally enqueue retry / dead-letter logic.
Minimal error workflow
Error Trigger
→ Edit Fields (build alert message from execution + error data)
→ Slack (post to #incidents)
Or, more featurefully, fetch the actual execution to recover the input data that caused the failure:
Error Trigger
→ n8n (resource: execution, operation: get,
executionId: {{ $json.execution.id }},
options.activeWorkflows: true) ← includeData=true on the API
← REQUIRES an "n8n API" credential
(Settings → API → create personal access token,
then attach via the node's Credential field)
→ Edit Fields (extract failed-node input from execution data)
→ Switch (route by severity)
├── high → PagerDuty
├── med → Slack #incidents
└── low → Slack #monitoring
→ Data Table Insert (log for tracking)
The Error Trigger payload only carries the error message, the failed node name (lastNodeExecuted), and the execution URL. It does not include the input data that caused the failure. The n8n node with Get Execution + Include Execution Details: true fills that gap by hitting GET /executions/{id}?includeData=true and returning the full run data, so you can pluck the failed node's input out of data.resultData.runData[<lastNodeExecuted>][0].source (or its inputs in executionData.nodeExecutionStack for more depth).
Why it's worth the extra step:
- The on-call message can include the actual offending payload, not just "node X errored".
- If you triage by input shape (which customer, which order ID), you skip a step in the n8n UI.
Caveats:
- Requires an n8n API credential on the error workflow. Create one under Settings → API (personal access token), then attach it to the n8n node's Credential field. Without it the node fails with a 401, which means an unhandled error in the error workflow itself.
- Requires the failing workflow to have Save Execution Data enabled (instance default or per-workflow setting; set it via
setWorkflowSettingssaveDataErrorExecution/saveDataSuccessExecution). If executions aren't persisted, the API returns the metadata only. - The n8n node call itself can fail (API down, rate-limited). Wire its error output to a fallback that still notifies, otherwise the original error vanishes.
Minimal is enough for most cases. The featureful version pays off in production-critical workflows where on-call time matters.
Setting it up
Set it via update_workflow setWorkflowSettings.errorWorkflow (the target workflow's ID). Validated server-side: the target must exist, be published, and contain an active Error Trigger node, else the update is rejected. Pass "DEFAULT" to clear. (n8n 2.29.0+; older instances set it in the workflow settings panel.)
What the error workflow should not do
- Make external API calls that can themselves fail. If your error workflow fails, the original error silently disappears.
- Take significant time. Runs synchronously, so slow error workflows compound the original failure's impact.
Keep error workflows fast: parse, notify, return.
Avoiding the recursion trap
If your error workflow uses Slack and Slack is down, the error workflow fails too. n8n won't re-trigger on its own failure (no infinite loop), but the failure goes nowhere.
Mitigations:
- Use a different channel than the monitored workflows. If most workflows notify Slack, the error workflow should use email.
- Have a fallback: write to a Data Table if the primary notification fails.
- Configure instance-level logging (server logs, Sentry) so even error-workflow failures surface.
What to put in the alert
Good notifications include:
- Workflow name:
{{ $json.workflow.name }} - Workflow ID:
{{ $json.workflow.id }} - Workflow link:
{{ $json.execution.url.split('/executions/')[0] }}(the execution URL is{base}/workflow/{id}/executions/{execId}, so stripping the tail gives the editor URL) - Execution ID:
{{ $json.execution.id }} - Execution link:
{{ $json.execution.url }}(opens the failed run directly) - Failed node name:
{{ $json.execution.lastNodeExecuted }} - Error message:
{{ $json.execution.error.message }}(real, not generic) - Error description:
{{ $json.execution.error.description }}(often empty, useful when set) - Timestamp:
{{ DateTime.fromMillis($json.execution.error.timestamp).toISO() }}(the payload'stimestampis a Unix ms number, format with Luxon) - Severity: derived from your routing logic, not on the payload
Bad: "Workflow failed."
Good (Slack body, expression-driven, both links present):
Workflow failure: *{{ $json.workflow.name }}* (`{{ $json.workflow.id }}`)
Workflow: {{ $json.execution.url.split('/executions/')[0] }}
Failed node: `{{ $json.execution.lastNodeExecuted }}`
Error: {{ $json.execution.error.message }}
Execution: {{ $json.execution.url }}
Time: {{ DateTime.fromMillis($json.execution.error.timestamp).toISO() }}
Two links matter: the workflow link so on-call can open the editor to start fixing, and the execution link so they can see the exact run that broke. Skipping either costs a step.
A "likely cause" line is optional, but for known failure modes a hint saves the on-call ten minutes.
When error workflows fire
Fires when:
- A node throws unhandled (not routed via per-node error output).
- The workflow itself fails (timeout, OOM).
- The trigger fails (rare, possible for non-webhook triggers).
Does not fire when:
- A node's error output is wired and the error is "handled" (even if the handler does nothing).
- You manually stop an execution.
- A workflow is paused / inactive.
So per-node error outputs that drop errors silently (e.g., wired to a no-op Set node) will not trigger the error workflow. The error has been "handled" from n8n's perspective, even though it's been swallowed.
For unhandled errors to bubble up, don't catch them per-node unless you're actively doing something with them.
Verifying the error workflow
After setup:
- Build a test workflow that always fails (HTTP Request to an invalid URL with no error output wired).
- Run it.
- Confirm the error workflow fires and the notification arrives.
Catches setup mistakes (wrong workflow assigned, wrong channel, missing credentials). Do this before relying on alerting.
Drift watch
Error Trigger payload shape can change between versions. If fields aren't where this file says, check current n8n docs and update parsing.
Open this reference as its own page
Per-node error outputs
About wiring an error output on an individual node: the second main output that fires when the node throws. For workflow-level error handling (catch-all workflows, webhook → respond), see the rest of n8n-error-handling-official.
Two-step setup
Always two changes. One without the other looks complete but misbehaves.
Step 1: configure the node
Set onError: 'continueErrorOutput'. Without this, the node has no error output, and main[1] doesn't exist regardless of wiring.
{
// ...other params...
onError: 'continueErrorOutput',
}
Other valid onError values:
'stopWorkflow'(default): error halts the whole workflow'continueRegularOutput': error data flows out the regular output (rare, usually wrong)'continueErrorOutput': error data flows out a separate error output (the one you wire below)
Step 2: wire output(1) to a handler
With onError: 'continueErrorOutput', the node has two outputs:
output(0): success pathoutput(1): error path
.add(node.output(0).to(successPath))
.add(node.output(1).to(errorHandler))
Or with the convenience handler:
.add(node.onError(errorHandler)) // same as .add(node.output(1).to(errorHandler))
Common shapes
Single fallible node with error branch
const sheets = node({
type: 'n8n-nodes-base.googleSheets',
config: {
parameters: { /* ...sheet config... */ },
onError: 'continueErrorOutput',
},
})
const respond = node({
type: 'n8n-nodes-base.respondToWebhook',
config: { parameters: { /* 5xx structured body */ } },
})
workflow
.add(webhook.output(0).to(sheets))
.add(sheets.output(0).to(successResponse))
.add(sheets.output(1).to(respond)) // error path
Fan-out on the success path with error branch
.add(sheets.output(0).to(successA))
.add(sheets.output(0).to(successB))
.add(sheets.output(1).to(errHandler))
Multiple fallible nodes routing to a shared error handler
.add(nodeA.output(1).to(errorHandler))
.add(nodeB.output(1).to(errorHandler))
.add(nodeC.output(1).to(errorHandler))
// Each node needs onError: 'continueErrorOutput' on its config.
Failure modes
onError set, error output not wired
const sheetsBroken = node({
type: 'n8n-nodes-base.googleSheets',
config: {
onError: 'continueErrorOutput',
// no error wire
},
})
On error, the node emits to main[1] with no targets. Error data is silently discarded, downstream doesn't fire, and the workflow appears to succeed (because the error was "handled" by a non-existent branch). One of the worst silent-failure modes in n8n: looks fine in the dashboard, no execution failure logged.
Fix: wire output(1) to a real handler, or change onError back to stopWorkflow so failures are loud.
Error wire set, onError not configured
const sheetsMissingOnError = node({
type: 'n8n-nodes-base.googleSheets',
config: {
// missing onError
},
})
.add(sheetsMissingOnError.output(1).to(errHandler))
The wire exists in the JSON but the slot never fires, and the handler is unreachable. On failure, the workflow stops (default onError: stopWorkflow).
Fix: add onError: 'continueErrorOutput' to the node config.
Mixing .onError(handler) with output(1) on the same node
Composes without conflict. Both wires are present.
.add(node.onError(loggerNode))
.add(node.output(1).to(respondNode))
// Both loggerNode and respondNode receive the error data.
Intentional: useful for both logging and a user-facing response on failure.
Verification
After create/update, pull via get_workflow_details and check both halves:
- Node config:
"onError": "continueErrorOutput"(or whatever you set). - Connections:
connections[node].main[1]contains the expected handler(s).
Either half missing = silent failure.
When to use error workflows instead
Per-node error outputs handle one node's failure. They don't catch:
- Crashes outside any node (rare).
- Errors on nodes without wired error outputs.
- Whole-workflow timeouts.
For those, configure a workflow-level error workflow. See the rest of n8n-error-handling-official.
Open this reference as its own page
Response shapes
Conventions for webhook API response bodies, both success and error. Pick a shape and stick to it across workflows on the same instance. Predictable responses make consumers (humans, dashboards, retry logic) easier.
This file is opinions. Adjust to your team's existing conventions. Consistency within a project beats consistency with this skill.
Match what's already on the instance
Before adopting the shapes below, search for existing API workflows on the instance and reuse their conventions. Inconsistency across endpoints is worse than any specific choice, and a one-off custom shape is hard to undo once callers depend on it.
search_workflows({ query: 'webhook' })
search_workflows({ query: 'API' })
search_workflows({ query: '<your domain>: ' }) # if the project uses domain prefixes
For each result, open get_workflow_details and look at how its Respond to Webhook nodes are shaped:
- Top-level keys (envelope vs bare, presence of
error/message, presence ofrequest_id). - Whether success bodies wrap the payload or return it bare.
- Error code strings already in use (
validation_errorvsbad_requestvsINVALID_INPUT). - Header conventions (
Content-Type,Retry-After,X-Request-Id).
If results are sparse, mixed, or you're unsure whether a project convention exists, ask the user before locking in a shape. One quick "I see endpoints A and B use shape X but endpoint C uses shape Y, which is the house style?" saves a future migration. Don't invent a domain prefix or convention from nothing.
The same rule applies upward: if your repo or company has a documented public API style, that wins over both this file and the instance.
The default success shape
Return the data bare. For requests that create or update a resource, the strong preference is to return the full resource's fields with a 200 status, not a bare { "ok": true } or just the new ID. Returning the resource saves the caller a follow-up GET, lets them confirm what actually got persisted (server-set defaults, normalized values, generated timestamps), and makes the endpoint usable as a single round-trip in UIs that immediately render the result.
{
"customer_id": "cus_123",
"balance": 4200,
"currency": "USD",
"created_at": "2026-04-25T12:34:00Z"
}
Only deviate from this when:
- The resource is genuinely large and the caller doesn't need it (then return only the ID, document why).
- The operation has no resource (event ingestion, fire-and-forget):
{}or204 No Contentis fine.
If a payload is genuinely list-shaped, return a top-level array or an explicit { "items": [...] } (the second is friendlier to future pagination metadata).
The default error shape
{
"error": "<machine-readable error code>",
"message": "<human-readable explanation>"
}
erroris a stable string identifier (not a sentence). Clients can branch on it.messageis the human version. Safe to log, safe to show users (after sanitization).- The HTTP status code already separates success from failure, so no
ok: falseflag is needed.
Optional fields by case:
| Field | When to include |
|---|---|
details |
Validation errors with field-by-field problems |
retry_after |
Rate limits (Retry-After header should also be set) |
documentation_url |
Public APIs where you want callers to RTFM |
Error codes
Pick from a small, stable set. Adding a new code is fine, but renaming an existing one breaks callers.
4xx (caller's fault)
| Code | Meaning |
|---|---|
validation_error |
Required field missing, type wrong, etc. |
invalid_input |
Field is present but value is invalid |
unauthorized |
No auth or expired auth |
forbidden |
Authenticated but not allowed |
not_found |
Resource doesn't exist |
conflict |
Operation conflicts with current state (duplicate key, etc.) |
rate_limit_exceeded |
Too many requests |
unsupported_media_type |
Content-Type wrong |
5xx (your fault)
| Code | Meaning |
|---|---|
internal_error |
Catch-all, something failed unexpectedly |
upstream_error |
Third-party API returned an error |
upstream_timeout |
Third-party API didn't respond |
service_unavailable |
Workflow temporarily can't process (you're down or rate-limited upstream) |
not_implemented |
Operation not supported in current version |
Validation error details
For 400/validation_error, include per-field details. Real example produced by the Set-based schema validator pattern (see below):
{
"error": "validation_error",
"message": "Validation failed (3 issues):\n• name: Missing required field \"name\"\n• email: \"not-an-email\" is not valid - Contact email address\n• plan: \"premium\" is not an allowed value. Must be one of: starter, pro, enterprise - Subscription plan",
"request_schema": { /* the JSON Schema, echoed back for caller-side self-correction */ }
}
message is the human summary (safe to show users), details is the structured per-field map (safe to map to UI fields), and request_schema is an optional echo useful for LLM-driven retries. Don't roll this by hand: see examples/validation-subworkflow.ts and examples/validation-subworkflow-usage.ts, with the full procedure in API_WORKFLOWS.md.
Rate limit responses
For 429 / rate_limit_exceeded:
{
"error": "rate_limit_exceeded",
"message": "Too many requests. Retry after 30s.",
"retry_after": "2026-05-08T21:10:05.135Z"
}
Also set the HTTP Retry-After header. Well-behaved clients respect the header without parsing the body.
What NOT to put in error responses
Stack traces
{ "error": "internal_error", "stack": "Error at line 42 of /opt/..." }
❌ Reveals server internals: paths, version info, library names. Useful for attackers, useless for callers. Log internally, return a generic message.
Upstream errors verbatim
{ "error": "upstream_error", "details": "<verbatim upstream response body>" }
❌ Upstream might embed their own internals: tokens, PII. Sanitize: surface "upstream service failed" with a request ID, and details go in your logs.
SQL queries
{ "error": "internal_error", "query": "SELECT * FROM users WHERE id = ..." }
❌ Same problem. Worse: exposes schema and access patterns.
Tokens, credentials, or auth values
Even innocuous-looking fields (headers, config, request) can leak token values. Audit error responses carefully. Leaks are easier than expected.
SDK shape for Respond to Webhook
const respondSuccess = node({
type: 'n8n-nodes-base.respondToWebhook',
config: {
parameters: {
responseCode: 200,
responseBody: '={{ JSON.stringify($json) }}',
options: {
responseHeaders: {
entries: [
{ name: 'Content-Type', value: 'application/json' },
],
},
},
},
},
})
const respondError = node({
type: 'n8n-nodes-base.respondToWebhook',
config: {
parameters: {
responseCode: 502,
responseBody: '={{ JSON.stringify({ error: "upstream_error", message: "External service failed" }) }}',
options: {
responseHeaders: {
entries: [
{ name: 'Content-Type', value: 'application/json' },
],
},
},
},
},
})
Always set Content-Type: application/json explicitly. Default behavior depends on responseBody shape and isn't reliable.
More in this playbook
Safe to turn on
Use this skill when an agent or person is about to create, change or enable an automation inside someone else's account or a shared environment: "create this workflow", "build it in the customer's account", "turn it on", "go live", "deploy this automation". Produces a proposal the human approves, an automation created in the off state, and a short list of what only the human can finish.
Workflow buildingMITn8n agents
Design n8n AI agents the right way. Use when building or editing any @n8n/n8n-nodes-langchain.* AI node — an AI Agent, LLM chain, Text Classifier, or Information Extractor — and whenever the user mentions AI agents, LLM with tools, tool calling, $fromAI, system prompts, agent memory, sessionId, structured/JSON output, output parser, RAG, vector store, a chat assistant/bot, or human-in-the-loop review. Covers Agent-vs-chain-vs-classifier choice, the model/memory/tools/outputParser slots, tool names/descriptions as prompt, structured output with autoFix, memory, RAG, human review, and chat topologies.
Workflow buildingMITn8n agents
Design n8n AI agents the right way. Use when building or editing any @n8n/n8n-nodes-langchain.* AI node — an AI Agent, LLM chain, Text Classifier, or Information Extractor — and whenever the user mentions AI agents, LLM with tools, tool calling, $fromAI, system prompts, agent memory, sessionId, structured/JSON output, output parser, RAG, vector store, a chat assistant/bot, or human-in-the-loop review. Covers Agent-vs-chain-vs-classifier choice, the model/memory/tools/outputParser slots, tool names/descriptions as prompt, structured output with autoFix, memory, RAG, human review, and chat topologies.


