Sane DOMParser Errors
sane-domparser-error is a JavaScript utility library designed to standardize error handling for DOMParser and XMLHttpRequest (when `responseType = 'document'`) in web environments. Typically, when an XML document cannot be parsed, these native APIs do not throw an exception but instead return a document containing a `<parsererror>` element. This library abstracts away the inconsistencies of the `<parsererror>` document across different browsers, providing a consistent mechanism to detect and report parsing failures as standard JavaScript `Error` objects. The package is currently at version 0.2.0, with its last update over a decade ago, indicating a maintenance status with a very infrequent release cadence. Its primary differentiator is simplifying robust XML parsing error detection, which is complex due to browser-specific `parsererror` document structures and namespaces.
Common errors
-
Uncaught ReferenceError: DOMParser is not defined
cause Attempting to use `DOMParser` (and by extension `sane-domparser-error`) in a Node.js environment where the Web API is not natively available.fixInstall and configure a DOM polyfill such as `jsdom` or `@xmldom/xmldom` in your Node.js application to provide a global `DOMParser` implementation. `const { JSDOM } = require('jsdom'); global.DOMParser = new JSDOM().window.DOMParser;` -
XML document parsed successfully, but it's malformed and no error was thrown.
cause The native `DOMParser.parseFromString()` method does not throw an exception on malformed XML. It returns a document containing a `<parsererror>` element, which needs to be explicitly checked.fixAfter parsing, always pass the resulting document to `saneError.failOnParseError(doc);` within a `try...catch` block to ensure that parsing errors are converted into throwable JavaScript errors.
Warnings
- gotcha The native DOMParser and XMLHttpRequest APIs do not throw JavaScript exceptions when XML parsing fails. Instead, they return a Document object containing a `<parsererror>` element. This package exists specifically to normalize this behavior into standard error throwing. Developers must explicitly check for these error documents or use this package.
- gotcha The structure and namespace of the `<parsererror>` element can vary slightly between different browsers (e.g., Firefox vs. Chrome-based browsers), making cross-browser error detection complex. This package aims to abstract these differences.
- gotcha This package is intended for browser environments. When attempting to use DOMParser in Node.js, you will encounter a `ReferenceError: DOMParser is not defined` because `DOMParser` is a Web API. This package does not provide a DOMParser polyfill for Node.js.
Install
-
npm install sane-domparser-error -
yarn add sane-domparser-error -
pnpm add sane-domparser-error
Imports
- saneError
import saneError from 'sane-domparser-error';
const saneError = require('sane-domparser-error'); - failOnParseError
import { failOnParseError } from 'sane-domparser-error';const saneError = require('sane-domparser-error'); saneError.failOnParseError(doc);
Quickstart
const saneError = require('sane-domparser-error');
// Simulate an invalid XML string
const malformedXml = '<root><item>Missing end tag</item>';
// Create a DOMParser instance (globally available in browsers)
const parser = new DOMParser();
// Attempt to parse the malformed XML
const doc = parser.parseFromString(malformedXml, 'application/xml');
try {
// Use sane-domparser-error to check for and throw an error
// if the document contains a parsererror element.
saneError.failOnParseError(doc);
console.log('XML parsed successfully (this should not happen with malformed XML).');
} catch (error) {
console.error('XML Parsing Error Caught:');
console.error(`- Error Message: ${error.message}`);
console.error(`- Error Name: ${error.name}`);
// In a real application, you might log the full stack or take recovery actions
}
// Example of valid XML for contrast
const validXml = '<root><item>Hello</item></root>';
const validDoc = parser.parseFromString(validXml, 'application/xml');
try {
saneError.failOnParseError(validDoc);
console.log('\nValid XML parsed successfully.');
} catch (error) {
console.error('\nUnexpected error with valid XML:', error.message);
}