diff --git a/README.md b/README.md index b641de6..00db262 100644 --- a/README.md +++ b/README.md @@ -60,10 +60,13 @@ fs.createReadStream(file) .on('data', function (obj) { //each chunk now is a js object }) + .on("error", function(error) => { + //handling parsing errors + }) ``` However, in [@dominictarr](https://github.com/dominictarr) [`split`](https://github.com/dominictarr/split) the mapper -is wrapped in a try-catch, while here it is not: if your parsing logic can throw, wrap it yourself. +is wrapped in a try-catch, while here it is not: if your parsing logic can throw, wrap it yourself. Otherwise, you can also use the stream error handling when mapper function throw. # Benchmark diff --git a/index.js b/index.js index b0b0421..fc2007b 100644 --- a/index.js +++ b/index.js @@ -40,7 +40,11 @@ function transform (chunk, enc, cb) { this[kLast] = list.pop() for (var i = 0; i < list.length; i++) { - push(this, this.mapper(list[i])) + try { + push(this, this.mapper(list[i])) + } catch (error) { + return cb(error) + } } this.overflow = this[kLast].length > this.maxLength @@ -54,7 +58,11 @@ function flush (cb) { this[kLast] += this[kDecoder].end() if (this[kLast]) { - push(this, this.mapper(this[kLast])) + try { + push(this, this.mapper(this[kLast])) + } catch (error) { + return cb(error) + } } cb() diff --git a/test.js b/test.js index fd743fc..e035787 100644 --- a/test.js +++ b/test.js @@ -152,7 +152,7 @@ test('splits a buffer', function (t) { test('do not end on undefined', function (t) { t.plan(2) - var input = split(function (line) {}) + var input = split(function (line) { }) input.pipe(strcb(function (err, list) { t.error(err) @@ -165,7 +165,7 @@ test('do not end on undefined', function (t) { test('has destroy method', function (t) { t.plan(1) - var input = split(function (line) {}) + var input = split(function (line) { }) input.on('close', function () { t.ok(true, 'close emitted') @@ -361,3 +361,32 @@ test("don't modify the options object", function (t) { input.end() }) + +test('mapper throws flush', function (t) { + t.plan(1) + var error = new Error() + var input = split(function () { + throw error + }) + + input.on('error', (err, list) => { + t.same(err, error) + }) + input.end('hello') +}) + +test('mapper throws on transform', function (t) { + t.plan(2) + + var error = new Error() + var input = split(function (l) { + throw error + }) + + input.on('error', (err) => { + t.same(err, error) + }) + input.write('a') + input.write('\n') + input.end('b') +})