From 79f3558d06cc3b851ac17384d469afa2fad23a92 Mon Sep 17 00:00:00 2001 From: samogot Date: Sun, 13 May 2018 02:19:53 +0300 Subject: [PATCH] Catch fatal xml/html parsing errors and pass them to callback Xml parsing is more strict and have more unrecoverable errors like absence of root element or multiply root elements. --- lib/Request.js | 13 +++++++++---- test/get.js | 20 +++++++++++++++++++- 2 files changed, 28 insertions(+), 5 deletions(-) diff --git a/lib/Request.js b/lib/Request.js index befe903..72974ef 100644 --- a/lib/Request.js +++ b/lib/Request.js @@ -51,10 +51,15 @@ function Request(method, url, params, opts, tries, callback) { var parse_mode = opts.parse_as; if (parse_mode === 'auto') parse_mode = getResponseType(res.headers['content-type']); - if (parse_mode === 'xml') - document = libxml.parseXml(document, { baseUrl: location.href, huge: true }); - else - document = libxml.parseHtml(document, { baseUrl: location.href, huge: true }); + try { + if (parse_mode === 'xml') + document = libxml.parseXml(document, {baseUrl: location.href, huge: true}); + else + document = libxml.parseHtml(document, {baseUrl: location.href, huge: true}); + } catch (e) { + callback('Response ' + parse_mode + ' parsing error: ' + e); + return; + } if (document === null) { callback('Couldn\'t parse response'); diff --git a/test/get.js b/test/get.js index 15bdc51..980500d 100644 --- a/test/get.js +++ b/test/get.js @@ -159,7 +159,7 @@ module.exports.multiple = function (assert) { }, 5000); } -module.exports.function_url = function (assert) { +module.exports.xml = function (assert) { osmosis.get(url + '/xml-auto') .then(function (context, data) { assert.equal(context.get('link').text(), 'http://example.com'); @@ -179,6 +179,24 @@ module.exports.function_url = function (assert) { }); }; +module.exports.error_xml_parse = function (assert) { + var tries = 4; + + osmosis.get(url + '/get') + .config('parse_as', 'xml') + .config('tries', tries) + .error(function (msg) { + // Multiply root elements are not allowed + if (msg.indexOf('parsing error') > -1) { + tries--; + } + }) + .done(function () { + assert.strictEqual(tries, 0); + assert.done(); + }); +}; + module.exports.absentQueryString = function (assert) { var found = false; osmosis.get(url + '/test-query-string')