wrappers for async callbacks that implement common error handling scenarios
Function wrappers for async callbacks that implement common, simple error handling scenarios.
npm install callback-wrappers
Most async methods in the node world expect a callback with an
(error, data) signature.
In programming scenarios where complex error handling is impossible or unneccessary (for
example you can simply log the error and exit the process) this can generate a lot
of repetitive, boilerplate, error-handling code that can obscure your real logic, e.g.
asyncFunction1if errorconsole.errorerror;processexit1;else// some real logic hereasyncFunction2if errorconsole.errorerror;processexit2;else// some more real logic here;;
This module provides a bunch of wrappers that take a function with just
and produce a function with the
(error, data) signature and the boiler plate logic in place.
For example the
exitIfError wrapper has the exact logic shown above, allowing for us to
collapse that example down to
var exitIfError = require"callback-wrappers"exitIfError;asyncFunction1 exitIfError1// some real logic hereasyncFunction2 exitIfError2// some more real logic here;;
There's also a
nextIfError wrapper that takes a function with a
next is a callback of the
(error, ...) variety). This simply
next (and, unlike the other methods, does not log).
If messing with built-in objects' prototypes doesn't skeeve you out, you can use
Function() export to get Function.prototype decorated with all of the wrappers
and our example can look like
require"callback-wrappers"Function;asyncFunction1// some real logic hereasyncFunction2// some more real logic hereexitIfError2;exitIfError1;
The wrappers all follow a naming convention of
action is one of
next. For brevity these
can be referenced by the initials
n, followed by
(for "If Error"). Note that in all cases the error is logged, and in no case,
logIfError, will the wrapped function be called if the
error parameter isn't empty.
- 0.3.0: added nextIfError
- 0.2.0: using Object.defineProperty to make the Function.prototype extensions not enumerable
- 0.1.0: created
Thanks go to the nodejs group for comments and suggestions.