{"record":{"id":"585a2d5b8da23d60","repo":"mermaid-js/mermaid","slug":"parsing-failed-lexererrors-parsererrors-585a2d","errorCode":null,"errorMessage":"Parsing failed: ${lexerErrors} ${parserErrors}","messagePattern":"Parsing failed: (.+?) (.+?)","errorType":"validation","errorClass":"MermaidParseError","httpStatus":null,"severity":"error","filePath":"packages/parser/src/parse.ts","lineNumber":147,"sourceCode":"export async function parse(diagramType: 'treemap', text: string): Promise<Treemap>;\nexport async function parse(diagramType: 'wardley', text: string): Promise<Wardley>;\nexport async function parse(diagramType: 'cynefin', text: string): Promise<Cynefin>;\n\nexport async function parse<T extends DiagramAST>(\n  diagramType: keyof typeof initializers,\n  text: string\n): Promise<T> {\n  const initializer = initializers[diagramType];\n  if (!initializer) {\n    throw new Error(`Unknown diagram type: ${diagramType}`);\n  }\n  if (!parsers[diagramType]) {\n    await initializer();\n  }\n  const parser: LangiumParser = parsers[diagramType];\n  const result: ParseResult<T> = parser.parse<T>(text);\n  if (result.lexerErrors.length > 0 || result.parserErrors.length > 0) {\n    throw new MermaidParseError(result);\n  }\n  return result.value;\n}\n\nexport class MermaidParseError extends Error {\n  constructor(public result: ParseResult<DiagramAST>) {\n    const lexerErrors: string = result.lexerErrors\n      .map((err) => {\n        const line = err.line !== undefined && !isNaN(err.line) ? err.line : '?';\n        const column = err.column !== undefined && !isNaN(err.column) ? err.column : '?';\n        return `Lexer error on line ${line}, column ${column}: ${err.message}`;\n      })\n      .join('\\n');\n    const parserErrors: string = result.parserErrors\n      .map((err) => {\n        const line =\n          err.token.startLine !== undefined && !isNaN(err.token.startLine)\n            ? err.token.startLine","sourceCodeStart":129,"sourceCodeEnd":165,"githubUrl":"https://github.com/mermaid-js/mermaid/blob/d93e9c88c01a599c062ee6a3f1462e3558ac6b90/packages/parser/src/parse.ts#L129-L165","documentation":"Thrown by parse() in packages/parser/src/parse.ts:147 as a MermaidParseError whenever the Langium parser for a beta diagram type (info, packet, pie, architecture, gitGraph, eventmodeling, radar, railroad, railroadEbnf, railroadAbnf, railroadPeg, treemap, treeView, wardley, cynefin) reports any lexerErrors or parserErrors. The constructor at parse.ts:152 formats each lexer error as 'Lexer error on line L, column C: msg' and each parser error as 'Parse error on line L, column C: msg', then joins them into 'Parsing failed: <lexerErrors> <parserErrors>'. It is the single unified, typed error surface for every Langium-backed diagram type; the raw ParseResult is exposed on error.result for programmatic inspection.","triggerScenarios":"Calling parse(diagramType, text) (or the railroad/ebnf/abnf/peg wrappers that also construct MermaidParseError) with text that violates the grammar for that diagramType. After parser.parse(text) returns, any non-empty result.lexerErrors or result.parserErrors (checked at parse.ts:146) triggers the throw. Concrete examples: radar-beta with 'axis my-axis my-axis2' (two identifiers on one axis), 'curve my-curve' with no matching axis entries, or an unlexable token like 'invalid@symbol'. Also thrown if diagramType is valid but the text is structurally incomplete (e.g. radar-beta followed only by 'axis').","commonSituations":"Copying old jison-era mermaid syntax into a beta diagram that now uses the Langium parser; typos in keywords ('axe' instead of 'axis'); supplying the wrong number of values (curve entry count vs axis count); grammar drift across mermaid versions; feeding user-authored or templated diagram text without validation; passing the wrong diagramType key for the text body.","solutions":["Read the embedded position in the message (e.g. 'Parse error on line 2, column 3') to locate the offending token.","Catch MermaidParseError and inspect error.result.lexerErrors and error.result.parserErrors for structured detail (messages, tokens, line/column).","Reduce the diagram to a minimal known-good example from the grammar docs, then re-add lines until it breaks to isolate the bad construct.","Confirm the diagramType argument matches a supported key in the initializers map (parse.ts:39) and that the text begins with the expected beta header token."],"exampleFix":"// before\nconst src = `radar-beta\n  axis my-axis my-axis2\n  curve c{1,2}`;\nawait parse('radar', src); // throws MermaidParseError: two identifiers on one axis\n\n// after\nconst src = `radar-beta\n  axis food[\"Food\"], service[\"Service\"]\n  curve a[\"A\"]{4,3}`;\nawait parse('radar', src);","handlingStrategy":"try-catch","validationCode":"// Light pre-check only; full grammar validation requires the Langium parser itself.\nfunction preflightLangiumParse(diagramType, text) {\n  if (!text || !text.trim()) throw new Error('empty diagram text');\n  const known = ['info','packet','pie','architecture','gitGraph','eventmodeling','radar','railroad','railroadEbnf','railroadAbnf','railroadPeg','treemap','treeView','wardley','cynefin'];\n  if (!known.includes(diagramType)) throw new Error('unsupported diagramType: ' + diagramType);\n}","typeGuard":"import { MermaidParseError } from '@mermaidjs/parser';\nfunction isMermaidParseError(e: unknown): e is MermaidParseError {\n  return e instanceof MermaidParseError;\n}","tryCatchPattern":"import { parse, MermaidParseError } from '@mermaidjs/parser';\ntry {\n  const ast = await parse('radar', src);\n} catch (e) {\n  if (e instanceof MermaidParseError) {\n    for (const pe of e.result.parserErrors) console.warn('parse', pe.token.startLine + ':' + pe.token.startColumn, pe.message);\n    for (const le of e.result.lexerErrors) console.warn('lex', le.line + ':' + le.column, le.message);\n    // surface a friendly message to the end user; do not crash the renderer\n  } else {\n    throw e;\n  }\n}","preventionTips":["Always await parse() (it is async and lazy-loads the diagram initializer); an unhandled rejection looks like a crash.","Treat any user-authored diagram text as untrusted and wrap render/parse in try-catch.","Pin your mermaid/parser version: grammar keywords and required sections change between releases.","Keep a known-good fixture per diagram type and regression-test generated text against it."],"tags":["parser","langium","syntax","mermaid","ast"],"backgroundTag":null,"analyzedSha":"d93e9c88c01a599c062ee6a3f1462e3558ac6b90","analyzedAt":"2026-08-12T06:23:11.304Z","schemaVersion":2},"datasetVersion":"2026-08-12T13:17:24.610Z"}