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.
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 = exitIfError;
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
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.
Thanks go to the nodejs group for comments and suggestions.