Skip to content

Error Codes

Complete reference of error codes returned by HTML Layout Parser.

Error Code Enum

typescript
enum ErrorCode {
  Success = 0,
  
  // Input validation (1xxx)
  InvalidInput = 1001,
  EmptyHtml = 1002,
  InvalidViewportWidth = 1003,
  InvalidMode = 1004,
  InvalidOptions = 1005,
  HtmlTooLarge = 1006,
  
  // Font errors (2xxx)
  FontNotLoaded = 2001,
  FontLoadFailed = 2002,
  FontDataInvalid = 2003,
  FontNameEmpty = 2004,
  FontIdNotFound = 2005,
  NoDefaultFont = 2006,
  FontMemoryExceeded = 2007,
  
  // Parse errors (3xxx)
  ParseFailed = 3001,
  DocumentCreationFailed = 3002,
  RenderFailed = 3003,
  LayoutFailed = 3004,
  CssParseError = 3005,
  
  // Memory errors (4xxx)
  MemoryAllocationFailed = 4001,
  MemoryLimitExceeded = 4002,
  
  // Internal errors (5xxx)
  InternalError = 5001,
  SerializationFailed = 5002,
  UnknownError = 5999
}

Error Categories

Input Validation Errors (1xxx)

CodeNameDescriptionSolution
1001InvalidInputInput HTML is invalidCheck HTML syntax
1002EmptyHtmlHTML string is emptyProvide non-empty HTML
1003InvalidViewportWidthViewport width is invalidUse positive number
1004InvalidModeOutput mode is invalidUse 'flat', 'byRow', 'simple', or 'full'
1005InvalidOptionsParse options are invalidCheck options object
1006HtmlTooLargeHTML exceeds size limitSplit into smaller chunks

Font Errors (2xxx)

CodeNameDescriptionSolution
2001FontNotLoadedNo fonts are loadedLoad at least one font
2002FontLoadFailedFont loading failedCheck font file format
2003FontDataInvalidFont data is corruptedUse valid TTF/OTF
2004FontNameEmptyFont name is emptyProvide font name
2005FontIdNotFoundFont ID doesn't existCheck font ID
2006NoDefaultFontNo default font setCall setDefaultFont()
2007FontMemoryExceededFont memory limit exceededUnload unused fonts

Parse Errors (3xxx)

CodeNameDescriptionSolution
3001ParseFailedHTML parsing failedCheck HTML syntax
3002DocumentCreationFailedDocument creation failedCheck HTML structure
3003RenderFailedRendering failedCheck CSS and fonts
3004LayoutFailedLayout calculation failedSimplify HTML/CSS
3005CssParseErrorCSS parsing errorCheck CSS syntax

Memory Errors (4xxx)

CodeNameDescriptionSolution
4001MemoryAllocationFailedMemory allocation failedFree memory, reduce load
4002MemoryLimitExceededMemory limit exceededUnload fonts, reduce batch size

Internal Errors (5xxx)

CodeNameDescriptionSolution
5001InternalErrorInternal parser errorReport bug
5002SerializationFailedOutput serialization failedCheck output mode
5999UnknownErrorUnknown error occurredCheck logs, report bug

Error Handling

Basic Error Handling

typescript
import { HtmlLayoutParser, ErrorCode } from 'html-layout-parser';

const parser = new HtmlLayoutParser();
await parser.init();

try {
  const result = parser.parseWithDiagnostics(html, { viewportWidth: 800 });
  
  if (!result.success) {
    for (const error of result.errors || []) {
      switch (error.code) {
        case ErrorCode.FontNotLoaded:
          console.error('Please load a font first');
          break;
        case ErrorCode.InvalidViewportWidth:
          console.error('Viewport width must be positive');
          break;
        default:
          console.error(`Error ${error.code}: ${error.message}`);
      }
    }
  }
} finally {
  parser.destroy();
}

Handling Warnings

typescript
const result = parser.parseWithDiagnostics(html, { viewportWidth: 800 });

if (result.warnings && result.warnings.length > 0) {
  for (const warning of result.warnings) {
    console.warn(`Warning: ${warning.message}`);
    
    if (warning.line && warning.column) {
      console.warn(`  at line ${warning.line}, column ${warning.column}`);
    }
  }
}

Error Recovery

typescript
async function parseWithRecovery(html: string): Promise<CharLayout[] | null> {
  const parser = new HtmlLayoutParser();
  
  try {
    await parser.init();
    
    // Try to load font
    try {
      const fontData = await loadFont('/fonts/arial.ttf');
      parser.loadFont(fontData, 'Arial');
      parser.setDefaultFont(1);
    } catch {
      // Try fallback font
      const fallbackData = await loadFont('/fonts/fallback.ttf');
      parser.loadFont(fallbackData, 'Fallback');
      parser.setDefaultFont(1);
    }
    
    const result = parser.parseWithDiagnostics(html, { viewportWidth: 800 });
    
    if (result.success) {
      return result.data as CharLayout[];
    }
    
    // Handle specific errors
    const fontError = result.errors?.find(e => 
      e.code === ErrorCode.FontNotLoaded || 
      e.code === ErrorCode.NoDefaultFont
    );
    
    if (fontError) {
      console.error('Font error - cannot recover');
      return null;
    }
    
    // For other errors, return partial result if available
    return result.data as CharLayout[] || null;
    
  } finally {
    parser.destroy();
  }
}

Severity Levels

Errors have three severity levels:

SeverityDescriptionAction
errorCritical error, parsing failedFix the issue
warningNon-critical issue, parsing continuedReview and fix if needed
infoInformational messageNo action required
typescript
const result = parser.parseWithDiagnostics(html, options);

// Filter by severity
const errors = result.errors?.filter(e => e.severity === 'error') || [];
const warnings = result.errors?.filter(e => e.severity === 'warning') || [];
const info = result.errors?.filter(e => e.severity === 'info') || [];

Released under the MIT License.