diff --git a/lib/util/xml.browser.ts b/lib/util/xml.browser.ts index 710e4f4f..260732a9 100644 --- a/lib/util/xml.browser.ts +++ b/lib/util/xml.browser.ts @@ -5,10 +5,7 @@ const parser = new DOMParser(); export function parseXML(str: string): Promise { try { const dom = parser.parseFromString(str, "application/xml"); - const errorMessage = getErrorMessage(dom); - if (errorMessage) { - throw new Error(errorMessage); - } + throwIfError(dom); const obj = domToObject(dom.childNodes[0]); return Promise.resolve(obj); @@ -17,13 +14,19 @@ export function parseXML(str: string): Promise { } } -const errorNS = parser.parseFromString("INVALID", "text/xml").getElementsByTagName("parsererror")[0].namespaceURI!; -function getErrorMessage(dom: Document): string | undefined { - const parserErrors = dom.getElementsByTagNameNS(errorNS, "parsererror"); - if (parserErrors.length) { - return parserErrors.item(0).innerHTML; - } else { - return undefined; +let errorNS = ""; +try { + errorNS = parser.parseFromString("INVALID", "text/xml").getElementsByTagName("parsererror")[0].namespaceURI!; +} catch (ignored) { + // Most browsers will return a document containing , but IE will throw. +} + +function throwIfError(dom: Document) { + if (errorNS) { + const parserErrors = dom.getElementsByTagNameNS(errorNS, "parsererror"); + if (parserErrors.length) { + throw new Error(parserErrors.item(0).innerHTML); + } } } @@ -73,7 +76,7 @@ const doc = document.implementation.createDocument(null, null, null); const serializer = new XMLSerializer(); export function stringifyXML(obj: any, opts?: { rootName?: string }) { - const rootName = (opts || {}).rootName || "root"; + const rootName = opts && opts.rootName || "root"; const dom = buildNode(obj, rootName)[0]; return '' + serializer.serializeToString(dom); } diff --git a/lib/xhrHttpClient.ts b/lib/xhrHttpClient.ts index f2c0f25e..ba5819a3 100644 --- a/lib/xhrHttpClient.ts +++ b/lib/xhrHttpClient.ts @@ -60,9 +60,9 @@ export class XhrHttpClient implements HttpClient { } } + xhr.open(request.method, request.url); xhr.timeout = request.timeout; xhr.withCredentials = request.withCredentials; - xhr.open(request.method, request.url); for (const header of request.headers.headersArray()) { xhr.setRequestHeader(header.name, header.value); } diff --git a/test/shared/xmlTests.ts b/test/shared/xmlTests.ts new file mode 100644 index 00000000..4d025e90 --- /dev/null +++ b/test/shared/xmlTests.ts @@ -0,0 +1,20 @@ +import { parseXML } from "../../lib/util/xml"; +import * as assert from "assert"; + +describe("XML serializer", function () { + it("should parse basic XML", async function() { + const res = await parseXML("42"); + assert.equal(res, 42); + }); + + it("should handle errors gracefully", async function () { + try { + await parseXML("INVALID"); + throw new Error("did not throw"); + } catch (err) { + if (err.message === "did not throw") { + throw err; + } + } + }); +});