Skip to content

Guide

Node-RED Subflows, Catch Node and Error Handling: Build Reliable Flows

Make Node-RED flows survive bad data and outages: subflows with properties, Link Call, Catch and msg.error, Status and watchdog nodes, retries, context and backups.

  • 6 min read
  • Updated November 2, 2026
Node-RED Subflows, Catch Node and Error Handling: Build Reliable Flows

Quick answer: a reliable Node-RED flow does four things. It validates every incoming message. It packages repeated logic into a subflow (select the nodes → Selection to Subflow), with per-instance settings read via env.get(). It splits a big canvas into sections joined by Link In / Link Out / Link Call nodes. And it routes failures to a Catch node, which receives msg.error, plus Status and watchdog nodes so a silent device or broker drop gets noticed. Add bounded retries (never infinite) and tested backups, and the flow survives bad data, outages and restarts.

ToolSolvesWhere
SubflowSame logic copied onto many flowsMenu → Subflows → Selection to Subflow
Subflow properties + env.get()Each copy needs its own settingsSubflow template → Properties tab
Link In / Link OutLong crossing wires, flows split across tabsCommon palette
Link CallReusable "function call" that returns a resultCommon palette (Node-RED 3.0+)
CatchErrors thrown by nodes disappearing silentlyCommon palette
StatusNoticing MQTT/serial disconnectsCommon palette
Trigger (watchdog)A device that just stops sendingFunction palette
Persistent contextCounters and state lost on restartcontextStorage in settings.js

1. Turn repeated logic into a subflow

If you have pasted the same validate-and-format nodes onto three sensor flows, a fix now needs three edits. A subflow holds the logic once; every instance updates when you edit the template.

  1. Select the nodes that repeat (for example json → validate → change).
  2. Menu → Subflows → Selection to Subflow. Node-RED replaces them with one subflow node and keeps the wires.
  3. Double-click the subflow instance → Edit subflow template to open it on its own tab.
  4. On the template's Properties tab, add settings that differ per use, for example MIN (number), MAX (number) and LABEL (string). Each instance then gets its own values in its edit dialog.
  5. Inside the subflow, read them with env.get("MIN") in a Function node, or choose env variable in any typed input such as a Switch or Change node.

A reusable range-check subflow (one input, two outputs: valid, rejected):

script.js
// Function node inside the subflow, Outputs: 2
const min = Number(env.get("MIN"));
const max = Number(env.get("MAX"));
const v = Number(msg.payload);
if (!Number.isFinite(v) || v < min || v > max) {
  msg.reason = env.get("LABEL") + ": out of range (" + msg.payload + ")";
  return [null, msg];          // output 2: rejected
}
msg.payload = v;
return [msg, null];              // output 1: valid

An unset property returns an empty string "", not undefined, so convert and check it. Add a Status node inside the subflow (send it {fill:"green", shape:"dot", text:"ok"}) to show a status under each instance on the main canvas.

Keep subflows to one responsibility ("validate a reading", "send an alert"), and name them by what they do.

2. Untangle the canvas with Link nodes

Link Out → Link In pairs are invisible wires: a message entering the Link Out appears at every Link In it's connected to, even on another tab. Use them to split a big flow into readable areas such as Inputs, Logic, Outputs and Errors, and put each area in a group with a clear name.

Link Call (Node-RED 3.0 and later) works like calling a function: it sends the message to a Link In, the target section processes it, and a Link Out set to "Return to calling link node" sends the result back to the exact Link Call that asked. That gives you one shared "format notification" or "lookup device name" routine used from many places, without the overhead of a subflow.

NeedUse
Same logic, different settings per copySubflow
One shared routine that returns a resultLink Call + Link In + Link Out (return mode)
Just tidy wiring between areas or tabsLink Out → Link In

3. Catch errors instead of losing them

When a node fails (a JSON parse error, an HTTP request timeout, a Function that throws), it reports an error. Without a Catch node, that error goes to the debug sidebar and log, and the message is dropped. With one, you get the failed message plus msg.error:

PropertyContains
msg.error.messageThe error text
msg.error.source.name / .type / .idWhich node failed
The rest of msgThe message that caused it, so you can retry or log it

Catch node scope options: all nodes on the tab, selected nodes, or nodes in the same group. Tick Ignore errors handled by other Catch nodes on a tab-wide "catch-all" so a specific handler takes priority.

A practical error branch: catch → function (format) → delay (rate limit: 1 msg/min, drop intermediate) → notification (Telegram, email, or a dashboard notification). The rate limit stops a broken sensor from sending you 500 alerts.

script.js
// Format a readable error alert
msg.payload = `Node-RED error in "${msg.error.source.name || msg.error.source.type}": ${msg.error.message}`;
return msg;

Make your own Function nodes catchable. Use node.error("Bad reading", msg), passing msg as the second argument. Without the message, the error is logged but Catch nodes never see it. node.warn() doesn't trigger Catch at all.

Watch connections with Status nodes

MQTT, serial and many other nodes report their connection state. A Status node set to watch your mqtt in node outputs msg.status.text such as node-red:common.status.connected or node-red:common.status.disconnected whenever it changes. Wire it to a dashboard text widget or an alert.

Notice devices that go quiet (watchdog)

Errors don't fire when a sensor just stops sending. Use a Trigger node as a watchdog: send nothing, then wait for 5 minutes, then send offline, with Extend delay if new message arrives ticked. Every reading restarts the timer; if readings stop for 5 minutes, you get one offline message. MQTT Last Will on the device is the other half of this: see ESP32 MQTT retained messages and LWT.

4. Validate at the edges, retry with limits

Treat every message from outside Node-RED (MQTT, HTTP, serial) as untrusted, even on your own LAN: check that it exists, has the right shape, and holds finite numbers in a sensible range. A missing reading is not zero, so drop it or flag it rather than letting a gauge or relay act on it.

script.js
// Validate an incoming sensor message; report bad ones to Catch nodes
const p = msg.payload;
if (!p || typeof p !== "object" ||
  typeof p.temperature_c !== "number" || !Number.isFinite(p.temperature_c) ||
  p.temperature_c < -40 || p.temperature_c > 125) {
  node.error("Rejected temperature message: " + JSON.stringify(p), msg);
  return null;
}
return msg;

Bounded retries. For an HTTP call that sometimes fails, catch the error, count attempts on the message, wait, and try again a limited number of times:

script.js
// In the error branch: retry up to 3 times, then give up
msg.retries = (msg.retries || 0) + 1;
if (msg.retries > 3) {
  node.warn("Giving up after 3 retries: " + msg.error.message);
  return [null, msg];      // output 2: alert / log
}
delete msg.error;
return [msg, null];          // output 1: delay node (e.g. 10 s) → back to the http request

Unlimited retry loops can hammer a service that's already down and flood your flow when it recovers.

Keep state across restarts. Context (flow.set(), global.set(), context.set()) lives in memory by default and is lost on restart or deploy. To persist it, add this to settings.js and restart:

script.js
contextStorage: {
  default: { module: "localfilesystem" }
},

Values are then written to disk (flushed every 30 seconds by default). Use it for counters, last-alert times and on/off states, but not for high-rate data, which belongs in a database.

5. Back up, version and test restores

  • Export a tab or the whole workspace from Menu → Export (choose JSON, formatted). Credentials are not included, which is good for sharing but means you need flows_cred.json and your credentialSecret to restore them.
  • Version control: enable Projects in settings.js (editorTheme: { projects: { enabled: true } }) to commit and diff flows with Git from inside the editor. Use a private repository.
  • Back up the runtime files from ~/.node-red: flows.json, flows_cred.json, settings.js, package.json (the list of palette nodes), and .config.runtime.json if you didn't set a credential secret. Full steps and a backup command: Secure Node-RED: HTTPS, MQTT TLS and backups.
  • Test a restore on a spare machine or a Docker container: copy the files, run npm install in the user directory, start Node-RED and check the flows deploy and connect.
  • Before upgrading Node-RED or a palette node, back up first and read the release notes.

Reliability checklist

CheckDone when
Input validationEvery MQTT/HTTP/serial input has a validate step; bad messages go to node.error(..., msg)
No silent failuresEach tab has a Catch node wired to a visible, rate-limited alert or log
Connection monitoringStatus nodes watch broker and serial connections
WatchdogsA Trigger watchdog (or MQTT Last Will) flags devices that go quiet
Bounded retriesEvery retry loop has a maximum count and a delay
Repeated logicShared logic lives in one subflow or Link Call routine
Persistent stateCounters and states that must survive a restart use file-backed context
Safe commandsCommands are explicit (ON/OFF, not TOGGLE) so repeating one is harmless
BackupsFlows, credentials, settings and package list backed up; restore tested

Troubleshooting

ProblemLikely causeFix
Catch node never firesFunction uses node.error("text") without msg, or node.warnUse node.error("text", msg)
Catch fires twice for one errorTwo Catch nodes with overlapping scopeTick Ignore errors handled by other Catch nodes on the catch-all
env.get() returns an empty stringProperty not defined on the subflow, or not set on that instanceAdd it on the template's Properties tab and set a default
Editing one subflow copy changed them allThat's how subflows workUse subflow properties for per-copy differences
Link Call times outTarget section doesn't end in a Link Out in "return" modeSet the final Link Out to Return to calling link node
Context values reset after restartDefault memory contextConfigure contextStorage with localfilesystem
Alert storm during an outageNo rate limit on the error branchAdd a Delay node in rate-limit mode, dropping intermediate messages
Status node shows nothingIt watches different nodes, or the node doesn't report statusSelect the node in the Status node's scope; check that node shows a status badge

FAQ

What is a subflow in Node-RED? A reusable group of nodes that appears as a single node in the palette. Edit the template once and every instance changes; per-instance settings come from subflow properties.

Subflow or Link Call? Use a subflow when each copy needs its own settings or its own state. Use Link Call when you want one shared routine, such as a lookup or formatter, that many flows call and get a result back from.

Can a subflow have a status? Yes. Add a Status node inside the subflow template (newer versions show it as a status output on the template) and send it a status object.

Do Catch nodes catch errors inside subflows? A Catch node inside the subflow handles its errors first. Errors not handled there are passed up to Catch nodes on the tab containing the subflow instance.

Next steps

Official references: Subflows, Handling errors and Working with context.

Continue learning

Related articles

All articles

Signal In

Built from what makers search for

The lookups piling up in SolderHub's search bar every day shape what we publish next — new component pages, board guides, and firmware notes, sent out as they go live.

By subscribing you agree to our Privacy Policy. Unsubscribe anytime.