Sane DOMParser Errors

0.2.0 · maintenance · verified Tue Apr 21

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

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to parse a malformed XML string using DOMParser and then utilize sane-domparser-error to catch and standardize the resulting parsing error into a throwable JavaScript Error object, contrasting it with successful parsing.

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);
}

view raw JSON →