Error Types
Parserator provides detailed, structured error information through theParseError type:
Expected Errors
Generated when specific tokens or patterns were expected:Unexpected Errors
Generated when unexpected input was encountered:Custom Errors
Generated with custom error messages:Fatal Errors
Non-recoverable errors that prevent backtracking:ParseErrorBundle
Multiple errors are collected in aParseErrorBundle:
Error Formatting
Plain Text
ANSI Colors (Terminal)
HTML
JSON
Custom Error Messages with expect()
Theexpect() method provides custom error messages:
user.domain.com
Output:
Controlling Backtracking with commit()
Thecommit() function prevents backtracking in choice combinators, leading to better error messages:
Without commit()
if (x > 5 { } (missing closing paren)
Error: Expected if, while, or for ❌ Not helpful!
With commit()
if (x > 5 { }
Error: Expected closing parenthesis ✅ Much better!
When to Use commit()
Usecommit() when:
- You’ve identified the type of construct being parsed (e.g., after a keyword)
- Backtracking would produce confusing error messages
- You want to fail fast with a specific error
cut()
Atomic Parsing
Theatomic() combinator makes parsing all-or-nothing:
- Preventing partial consumption in choice combinators
- Lookahead-style parsing
- Trying complex alternatives cleanly
Span Information
Every error includes aSpan indicating its location:
Context Stack
Parserator tracks parsing context for better error messages. Thelabel() method adds context:
Error Recovery
While Parserator doesn’t have built-in error recovery, you can implement it usingor() and custom parsers:
Creating Custom Errors
You can create custom errors usingParser.fatal() or Parser.fail():
Error Hints and Suggestions
Parserator can provide intelligent error suggestions. The error formatter automatically includes hints when appropriate:Best Practices
-
Use
.expect()for user-facing errors -
Use
commit()after identifying constructs -
Provide context with
.label() -
Use
atomic()for clean alternatives -
Format errors appropriately for your context
- Use
"ansi"for CLI tools - Use
"html"for web editors - Use
"json"for APIs
- Use