1

Rethrowing errors in JS is easy:

try {
    //some code that fails
} catch(e) {
    throw getMyOwnErrorObj(e);
}

How do I achieve this in nodejs streams. Afaik, I can only simply catch an error by listening to the error event of a stream. But how do I catch an error and rethrow that error (or a different error)? I could of course wrap streams with my own stream implementation that modifies the behaviour of the event emitter. But I'm looking for a more charming solution.

My use case:

  • I need to parse some files
  • The files may be gzipped, tarred, bzipped, something else, or a combination of these. The first x bytes of the stream are read to decide which stream to use first
  • As the order, type, and number of streams isnt fixed, I use pumpify to 'glue' the streams together. Pumpify combines an array of streams into a single duplex stream, with a single error event. I.e., this lib attaches another error listener to my streams.

A simplified example of what I'd like to work is:

var pumpify = require("pumpify");
var tar = require("tar-fs");
var zlib = require("zlib");
var fs = require("fs");

var untar = pumpify(
  zlib.createGunzip().on("error", function(e) {
    //I'd like to rethrow an error here, so other error event listeners will catch _my_ error
     //this below doesnt work (Maximum call stack size exceeded)
     this.emit('error', new MyError(e));
  }),
  tar.extract("output-folder")
);
fs.createReadStream("./some-file-that-isnt-gzipped").pipe(untar).on("error", function(e) {
  //I'd like e to be intanceof MyError here...
});

ps. Updated with use-case and example per latest comments

Laurens Rietveld
  • 958
  • 1
  • 11
  • 21

0 Answers0