errTo - simple error handling helper for Node.js/CoffeeScript/IcedCoffeeScript
Often in Node.js you need to check for 'err' parameter returned from async function. This small module helps dealing with this by calling error handler automatically.
Sample Usage (CoffeeScript)
# What you needed to write without errTo. Remember to check error after each and every async call. = fsreaddir catalog if err? then return callbackerr # <= This is evil. consolelog "Success!" callback nullfilenames # The unicorns come to the rescue. errTo = require 'errto' # Same function as above, with the errTo helper. = fsreaddir catalogerrTo callback # Notice no 'err' argument. # Error check is done automatically in errTo and callback(err) is called on error. # Subsequent code is called ONLY when no error given. consolelog "Success!" callback nullfilenames # Express sample. appget '/' readDirectoryAsync __dirnameerrTo next # Use Express error handling by calling next(err) ressend filenames
Sample Usage (JavaScript)
// What you needed to write without errTo. Remember to check error after each and every async call. { fs;} // The unicorns come to the rescue.var errTo = ; // Same function as above, with the errTo helper. { fs;} // Express sample.app;
Sample Usage (IcedCoffeeScript)
# Almost the same as in CoffeeScript errTo = require 'errto' appget '/' await dbgetUserById requserIderrTo nextdefer user # Notice, errTo is outside defer. resrender 'index'user appget '/posts/:postId' noErr = errTobindnullnext # errTo can be bound in the beginning, using standard JS construct. await dbgetPostById reqparam'postId'noErr defer post await # Notice these 2 requests will be run in parallel and if at least one of them fails (returns error) # then the whole block fails. But if both fail, then only the first error is kept. dbgetPostComments post_iderrTo nextdefer comments dbgetPostText post_iderrTo nextdefer text render 'post'commentstext
How it works
(See index.js, its only 19 LOC)
errTo function takes 2 arguments: errorHandler and successHandler. It returns a function which, when called, will check if its first argument (err) is truthy and call first or second function correspondingly. errorHandler is called with 'err' argument. successHandler is called with all but the 'err' argument.
Note, either errorHandler or successHandler will be called, and only once. All subsequent calls will be ignored. Also, a errorHandler will not be called more than once, even if wrapped by different calls to errTo. This is needed to provide protection when multiple commands are executing at the same time.
License: MIT