From 0382a0b2d72495fc89a6196e4eb4afd49aa513a0 Mon Sep 17 00:00:00 2001 From: Anton Medvedev Date: Thu, 4 Apr 2019 00:13:58 +0700 Subject: [PATCH] Catch stream errors gracefully --- stream.js | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/stream.js b/stream.js index 00db811..526b60d 100644 --- a/stream.js +++ b/stream.js @@ -1,5 +1,16 @@ 'use strict' +function apply(cb, input) { + let json + try { + json = JSON.parse(input) + } catch (e) { + process.stderr.write(e.toString() + '\n') + return + } + cb(json) +} + function stream(from, cb) { let buff = '' let lastChar = '' @@ -15,13 +26,11 @@ function stream(from, cb) { if (count > 0) { if (head !== '') { - const json = JSON.parse(head) - cb(json) + apply(cb, head) head = '' } - const json = JSON.parse(input) - cb(json) + apply(cb, input) } else { head = input }