查看管道错误

时间:2016-10-12 20:26:47

标签: node.js error-handling pipe

在下面的代码块中,如何记录导致JSONStream.parse失败的管道数据?

data.pipe(JSONStream.parse('*'))
.on('error', () => {
    // here I'd like to see the data causing JOSONStream.parse to blow up
    reject("Error parsing the json!");
})
.pipe(objectStream);

我问,因为目前当它爆炸时,我得到这种错误信息,但没有无效的UTF-8字符的上下文:

Error: Invalid JSON (Invalid UTF-8 character at position 2397 in state STRING1)
        at Parser.proto.write (/var/www/data-site/pop-service/node_modules/JSONStream/node_modules/jsonparse/jsonparse.js:120:31)
        at Stream.<anonymous> (/var/www/data-site/pop-service/node_modules/JSONStream/index.js:23:12)
        at Stream.stream.write (/var/www/data-site/pop-service/node_modules/JSONStream/node_modules/through/index.js:26:11)
        at IncomingMessage.ondata (_stream_readable.js:536:20)
        at emitOne (events.js:82:20)
        at IncomingMessage.emit (events.js:169:7)
        at readableAddChunk (_stream_readable.js:153:18)
        at IncomingMessage.Readable.push (_stream_readable.js:111:10)
        at HTTPParser.parserOnBody (_http_common.js:124:22)
        at TLSSocket.socketOnData (_http_client.js:320:20)
.on('error', (data) => {...这样的东西似乎不起作用

解决方案使用@drinchev的回答

    //save the last chunk so that we can log it in case of parsing error
    let lastRetrievedChunk = '';
    data.on('data', (dd: any) => {
      lastRetrievedChunk = dd.toString();
    });

    let jsonParser = JSONStream.parse('*');
    jsonParser.on('error', (err: any) => {
      reject(err.stack + ' lastchunk = ' + lastRetrievedChunk);
    });
    data.pipe(jsonParser).pipe(objectStream);

1 个答案:

答案 0 :(得分:0)

它确实不起作用,因为它是事件驱动的过程。

您可以尝试将数据存储在变量中并将其传递给错误

var someString = '*';

data.pipe(JSONStream.parse(someString))
    .on('error', () => {
       console.log( someString );
       reject("Error parsing the json!");
    })
    .pipe(objectStream);

您可以随时使用某些库through2,它可以帮助您制作记录管道数据的流。