I am in the process of making our nodes implement the new on('input')
signature of Node-RED v1.0. I also noticed the error handling is now done via done(err)
instead of node.error(err, msg)
.
If there are multiple return points or error handling locations, the proposed way from the docs and the blog can be quite verbose, because you'd always have to check if done
is defined.
So I did the same as Nick (@knolleary ) did with send
for the done
callback.
It's working in both pre-1.0 and 1.0 for me. The question is, did I overlook some edge cases?
If it's an approved solution, maybe this could be added to the docs as well.
Here's the verbose commented version:
done = done || function () {
// at least one argument -> 'done' is used as error notification
if (arguments.length > 0) {
// call node.error()
// use first arg as error object
// 'msg' is taken from closure
node.error.apply(node, [arguments[0], msg]);
}
// otherwise do nothing
};
And the modified example from the blog with the new done
as one-liner:
this.on('input', function (msg, send, done) {
// If this is pre-1.0, 'send' will be undefined, so fallback to node.send
send = send || function () { node.send.apply(node, arguments) }
done = done || function () { if (arguments.length > 0) { node.error.apply(node, [arguments[0], msg]); } };
// do some work with msg
someImaginaryLibrary(msg, (err, result) => {
if (err) {
// Report back the error
done(err);
} else {
msg.payload = result;
send(msg);
done();
}
})
})