Search code examples
javascriptnode.jserror-handlingxml2js

Is xml2js guaranteed to be synchronous and does it throw errors?


I am using xml2js and I need to be robust since there is no guarantee that the source of the xml is well-formed. So, I need to ensure that all errors are able to be handled. If the code looks something like this:

let parseString = require('xml2js').parseString;
let xml = getTheXml(...);
parseString(xml, (err, result) => {
    if (err) { handleError(err) }
    else { handleResult(result); }
});

Am I guaranteed that parseString will never throw an error and that all errors are passed through as an err object to the callback?

Or to be safer, do I need to do the following:

let parseString = require('xml2js').parseString;
let xml = getTheXml(...);
try {
  parseString(xml, (err, result) => {
    if (err) { handleError(err) }
    else { handleResult(result); }
  });
} catch (err) { handleError(err); }

Furthermore, am I guaranteed that parseString executes synchronously?


Solution

  • The expected behavior when there's a error-first-callback design implemented is that it's not synchronous and that any error is passed as the first argument.

    "Guaranteed".. I'm not the author or contributor to the module, so I can't say anything about that. If you need to make sure, write a test..