The caught value, of unknown type
The span, or undefined when none is available
import { getErrorSpan, isRollParserError, roll } from 'roll-parser';
function explain(notation: string): string | undefined {
try {
roll(notation);
return undefined;
} catch (error) {
if (!isRollParserError(error)) throw error;
const span = getErrorSpan(error);
if (span == null) return error.message;
const width = (span.end ?? span.start + 1) - span.start;
return [
error.message,
notation,
' '.repeat(span.start) + '^'.repeat(width),
].join('\n');
}
}
explain('2d6+&');
// Unexpected character: '&'
// 2d6+&
// ^
explain('2d6+1d0+3');
// Invalid dice sides: 0
// 2d6+1d0+3
// ^^^
Normalizes the three error position shapes into one span.
LexerErrorandParseErrorexpose a singleposition;EvaluatorErrorexposesstart/end. Returnsundefinedfor errors that are not roll-parser errors, or that carry no usable offset (anEvaluatorErrorraised on a hand-built AST, for instance).