4 ms·
Unfortunately, Node.js decided that every callback should accept an error as the first argument to every callback. If you're chaining a bunch of callbacks, it's
by jestar_jokin 11y ago
Unfortunately, Node.js decided that every callback should accept an error as the first argument to every callback. If you're chaining a bunch of callbacks, it's tedious and error-prone to add boilerplate to check for an error and handle it consistently in every callback, and violating the DRY principle. It's not easy to simply propagate the error to a higher-level handler.
- fao_ 11y agoIf you're repeating yourself, then you could possibly abuse higher class functions to automatically generate error handling?
- doublerebel 11y agoYes, there are libs like errTo [1] and iced-error/make_esc [2]. Not to mention Promise.promisify(). Long solved problem. [1]: https://www.npmjs.com/package/errto https://www.npmjs.com/package/errto [2]: https://www.npmjs.com/package/iced-error https://www.npmjs.com/package/iced-error
- apeace 11y agoI find the `async` library excels at this: var fs = require('fs'); var async = require('async'); async.waterfall([ (cb) => fs.readFile('foo.txt', cb), (data, cb) => my_function(data, cb), (result, cb) => myDb.lookup(result, cb), ], (err, finalResult) { if (err) { console.error(err); } else { console.log(finalResult); } }); There are all sorts of helpful async primitives in there. I don't write Javascript without it! Here is a link to the documentation: https://github.com/caolan/async https://github.com/caolan/async
- jjn2009 11y agoIts a problem yes, but the nature of javascript makes this a difficult problem to address. Node tried addressing this with the 'domain' module to help with propagating errors upward more generically: https://nodejs.org/api/domain.html https://nodejs.org/api/domain.html But it was deprecated: https://github.com/nodejs/node/issues/66 https://github.com/nodejs/node/issues/66 promises are a very nice way of drying out error handling and cleaning up callbacks for now.
- erikpukinskis 11y agoI would have to look at your code, but generally if you have a long callback chain and you're trying to propagate errors up it you are doing something wrong. Are you really working on 10 nested activities simultaneously, or are you just nesting things because it's convenient and you don't want to think about how to do things in stages? If you're trying to convince me that "callbacks become painful in situation X" you really don't need to. I know that. What I'm saying is that 9 times out of 10, the answer to the question "do we really want to be in situation X in the first place?" is "no". But instead of getting out of a bad situation by refactoring, people just write crazier and crazier control structures (i.e. promises) to make those bad situations workable.