在以下代码块中,如何记录导致 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);
我问,因为目前当它爆炸时,我收到这种错误消息,但没有关于 Invalid 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) => {...
似乎不起作用解决方案使用@dinchev 的回答
//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);
最佳答案
它确实不起作用,因为它是事件驱动的过程。
您可以尝试将数据存储在变量中并将其传递给错误
var someString = '*';
data.pipe(JSONStream.parse(someString))
.on('error', () => {
console.log( someString );
reject("Error parsing the json!");
})
.pipe(objectStream);
在任何时候,您还可以使用一些库,如 through2这可以帮助您制作一个记录管道数据的流。
关于node.js - 查看管道错误中的管道数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40007746/