From 577880737382fe852131d2a6410c39c1465ce0b8 Mon Sep 17 00:00:00 2001 From: Parsha Pourkhomami Date: Tue, 12 Jan 2016 16:31:35 -0800 Subject: [PATCH] Do not swallow errors thrown in callback Previously, if a synchronous error was thrown in the callback given to toArray, the error is swallowed and never makes its way up the stack as expected. This happens because the callback executes in a promise.then() callback stack trace. The promise implementation catches the error and doesn't report it other than via the "unhandledRejection" event. This is unexpected for someone that is not otherwise using promises in their application code. This change uses process.nextTick to remove the callback from the promise.then call stack. --- index.js | 4 +++- package.json | 3 ++- test/index.js | 22 ++++++++++++++++++++++ 3 files changed, 27 insertions(+), 2 deletions(-) diff --git a/index.js b/index.js index 1affd3a..164d9d5 100644 --- a/index.js +++ b/index.js @@ -50,7 +50,9 @@ module.exports = function (stream, done) { if (typeof done === 'function') { deferred.then(function (arr) { - done(null, arr) + process.nextTick(function() { + done(null, arr) + }) }, done) } diff --git a/package.json b/package.json index 8ca0f4a..fc0faa5 100644 --- a/package.json +++ b/package.json @@ -16,7 +16,8 @@ "devDependencies": { "bluebird": "^3.1.1", "istanbul": "0", - "mocha": "^2.3.3" + "mocha": "^2.3.3", + "trycatch": "^1.5.21" }, "scripts": { "test": "mocha --reporter spec --bail", diff --git a/test/index.js b/test/index.js index 05f9e6c..e5e245e 100644 --- a/test/index.js +++ b/test/index.js @@ -3,6 +3,7 @@ var assert = require('assert') var stream = require('stream') var path = require('path') var fs = require('fs') +var trycatch = require("trycatch") var toArray = require('..') @@ -60,6 +61,27 @@ describe('Stream To Array', function () { assert.equal(arr.length, 0) }) }) + + it('should not swallow errors', function (done) { + var id = {} + trycatch( + function () { + toArray(emptyStream(), function (err, arr) { + if (err) + return done(err) + + var err = new Error("foo") + err.id = id + throw err + }) + }, + function (err) { + assert(err); + assert.equal(err.id, id); + done(); + } + ) + }) }) describe('as a method', function () {