error check nested callbacks with domain support
Bubble errors back up your big ol' nested callback chain.
If domains are in use, defer the error to the domain's error handler by using
fsreadDirpathiferr return cberr;asyncmapfiles fsreadFileiferr return cberr;return cbnull contentsjoin'\n';;;;
var ok = require'okay';fsreadDirpath okcbasyncmapfiles fsreadFile okcbreturn cbnull contentsjoin'\n';;;;
The same code with annotations:
var ok = require'okay';//if path does not exist, bubble the error out to the//callback function right away//if there was no error, call the new error-less cbfsreadDirpath okcb//if there was an error reading any file, bubble the error out to the//callback function right away//if there was no error, call the new error-less cbasyncmapfiles fsreadFile okcbreturn cbnull contentsjoin'\n';;;;
okay also supports a single callback:
//if there is an error with fs.readDir, THROW it//if there was no error, call the new error-less callbackfsreadDirpath ok//if there was an error reading any file, THROW it//if there was no error, call the new error-less callbackasyncmapfiles fsReadFile okreturn callbacknull contentsjoin'\n';;;;
or even no callback at all:
//if there is an error with fs.writeFile, THROW it//if there was no error, do nothingfswriteFile'/some/file' 'hello' ok;
Throwing errors is probably not what you want to do.
Okay comes in really handy if you are using domains. It transparently passes the error back into the active domain if it exists, or it calls your callback with the error parameter already removed in the happy circumstance where there is no error. It's basically shorthand for
process.domain.intercept but will fall back to throwing exceptions if domains are not activated or you're currently not bound to a domain.
var ok = require'okay';var domain = require'domain';var count = 0;varvar requestDomain = domaincreate;reqid = + count++;requestDomainaddreq;requestDomainaddres;requestDomainon'error'console.log'error handling request ' + reqid;console.logerr;tryresend500;catcheconsole.log'could not send response 500 code';;processnextTicksetTimeout//read some missing file to cause an error//the error will fire on the request's domain//and WILL NOT crash the serverifcount % 2fsreadFile'omsdflksjdflsk' okreswriteHead200;resend'ok';;else//this exception will fire on the request's domain//as well and will also NOT crash the serverprocessnextTickokthrow "I Broke it.";1000;var serverDomain = domaincreate;serverDomainon'error'console.log'something happened with the server!'console.loge;;serverDomainrunvar http = require'http';var server = httpcreateServerhandler;serverlisten80;;
var ok = require'okay';get'/'fsreadFile'file.txt' 'utf8' oknextressendcontents;;;
ok = require "okay"app.get "/", (req, res, next) ->fs.readFile "file.txt", "utf8", ok next, (contents) ->res.send(contents)
var ok = require'okay';describe'a directory'it'exists'fsreaddir__dirname okdoneassertequal1 fileslength;done;;;;
code golf, baby.