简体   繁体   中英

Nodejs error handling in callback (xml-stream)

i use the xml-stream library for nodejs to parse a big xml file. 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.

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?

Or does xml-stream not providing that?

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

Does someone can explain me the reason and maybe how to fix that?

Thanks in advance!

Try adding a handler for the error event:

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 ? 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");
  );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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