简体   繁体   English

回调中的Node.js错误处理(xml-stream)

[英]Nodejs error handling in callback (xml-stream)

i use the xml-stream library for nodejs to parse a big xml file. 我使用xml-stream库来处理nodejs来解析一个大的xml文件。 That works very well. 效果很好。 But i notice, that if there is a problem like a RefereceError in the callback of a xml-stream event, nodejs is only quitting without notify me or throw an error. 但是我注意到,如果在xml流事件的回调中出现类似RefereceError的问题,nodejs只会退出而不通知我或抛出错误。

A short example is the following code: 一个简短的示例是以下代码:

var fs = require('fs');
var XmlStream = require('xml-stream');

var stream = fs.createReadStream('E:/jdown2/dblp/dblp.xml');
var xml = new XmlStream(stream);


xml.on('endElement: article', function (data) {
    console.log("article"); // works well
    var demo = functionThatNotExists(data);
    console.log("nodejs exit before this console log");
});

So my question is, how can i reach it, that nodejs tells me that there was an error and where the error occur? 所以我的问题是,我怎么能到达它,那个nodejs告诉我有一个错误以及错误发生在哪里?

Or does xml-stream not providing that? 还是xml-stream不提供那个?

In a normal callback function like: 在像这样的普通回调函数中:

errorInCallback("test", function (err,data) {
    console.log(err, data)
});

function errorInCallback(data, cb) {
    var demo = functionThatNotExists(data);
    var err = null;
    return cb(err, demo)
}

all works like expected and nodejs throws a ReferenceError 所有的工作都像预期的那样,并且nodejs抛出ReferenceError

Does someone can explain me the reason and maybe how to fix that? 有人可以向我解释原因,也许如何解决吗?

Thanks in advance! 提前致谢!

Try adding a handler for the error event: 尝试为error事件添加处理程序:

xml.on('error', function (err) {
    console.log(err);
});

Are you trying to call a function that doesn't exist with the data you are getting from xml.on ? 您是否要调用从xml.on获取的数据不存在的函数? If so, the error is coming from there and then so you should handle it. 如果是这样,则错误是从那里传来的,那么您应该处理它。

var fs = require('fs');
    var XmlStream = require('xml-stream');

var stream = fs.createReadStream('E:/jdown2/dblp/dblp.xml');
var xml = new XmlStream(stream);

xml.on('endElement: article', function (data) {
    console.log("article"); // works well
    try {
       var demo = functionThatNotExists(data);
       if (demo == null) {
         throw new Error('Something went wrong');
       }
    } 
    catch(e) {
     console.log(e.name + ": " + e.message);
    }

   console.log("nodejs exit before this console log");
  );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM