Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Stream's api methods must never throw - handling errors in DecodeStream, EncodeStream #81

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 7 additions & 3 deletions lib/decode-stream.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,11 @@ function DecodeStream(options) {
}

DecodeStream.prototype._transform = function(chunk, encoding, callback) {
this.decoder.write(chunk);
this.decoder.flush();
if (callback) callback();
try {
this.decoder.write(chunk);
this.decoder.flush();
} catch(e) {
return callback(e);
}
callback();
};
16 changes: 12 additions & 4 deletions lib/encode-stream.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,19 @@ function EncodeStream(options) {
}

EncodeStream.prototype._transform = function(chunk, encoding, callback) {
this.encoder.write(chunk);
if (callback) callback();
try {
this.encoder.write(chunk);
} catch(e) {
return callback(e);
}
callback();
};

EncodeStream.prototype._flush = function(callback) {
this.encoder.flush();
if (callback) callback();
try {
this.encoder.flush();
} catch(e) {
return callback(e);
}
callback();
};
37 changes: 37 additions & 0 deletions test/30.stream.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@ var encoded = [

var encodeall = Buffer.concat(encoded);

// invalid msgpack type
var invalencoded = Buffer([0xc1]);

describe(TITLE, function() {

it("msgpack.createEncodeStream()", function(done) {
Expand Down Expand Up @@ -116,4 +119,38 @@ describe(TITLE, function() {
if (++count === 3) done();
}
});

it("msgpack.createDecodeStream().on('error',fn)", function(done) {
var decoder = msgpack.createDecodeStream();

decoder.on("error", function(e) {
assert.ok(e instanceof Error, "should be an error");
setTimeout(done, 1);
});

decoder.on("data", function(data) {
assert.fail("should not emit data");
});

decoder.end(invalencoded);
});

it("msgpack.createEncodeStream().on('error',fn)", function(done) {
var circular = [];
var encoder = msgpack.createEncodeStream();

circular.push(circular);

encoder.on("error", function(e) {
assert.ok(e instanceof Error, "should be an error");
setTimeout(done, 1);
});

encoder.on("data", function(data) {
assert.fail("should not emit data");
});

encoder.end(circular);
});

});