1

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?

Andrew Eisenberg
  • 28,387
  • 9
  • 92
  • 148

1 Answers1

1

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..

superhero
  • 6,281
  • 11
  • 59
  • 91
  • I have written a test, but the test only ensures that the path it takes is synchronous. It does not test that other paths through the method are synchronous. Nor does it test that future versions of the package will remain synchronous. I am hoping to have a clarification on the package's API contract, which is something only one of the package dev's could answer. – Andrew Eisenberg May 08 '17 at 16:37
  • you should specify version in your `package.json` to secure your application against breaking changes in 3:d party libraries. – superhero May 08 '17 at 16:47
  • Fair point. I do this too, but knowing the contract behind the API would make me more confident when I do want to upgrade. I've inspected the code and I do feel confident that the parse method does not throw. I guess I need to assume that the library will use standard node callbacks. – Andrew Eisenberg May 09 '17 at 03:26
  • @AndrewEisenberg or contact them through github ;) https://github.com/Leonidas-from-XIV/node-xml2js – superhero May 09 '17 at 08:55