Skip to content
RANDSUMroller

Error Handling

roll() throws on invalid input. Valid notation written into your code, like roll('4d6L'), never throws: errors come from input outside your control.

roll() throws when given invalid input:

  • Invalid notation: ValidationError for a string that is not notation ('4dX', 'not dice')
  • Notation over a limit: NotationParseError for notation that parses but breaks a limit, such as a repeat count over 1000 ('1d6x5000')
  • Invalid options: ValidationError for bad option values (sides: 0, quantity: -1)
  • Modifier errors: ModifierError for out-of-range modifier arguments

All four extend RandsumError.

Valid-but-unusual inputs (like roll(1) for a single-sided die) are not errors.

Every error @randsum/roller throws extends RandsumError, which carries a code and an optional context.

Class Extends Code When
RandsumError Error varies Base class for roller errors
ValidationError RandsumError VALIDATION_ERROR Options object has invalid values
ModifierError RandsumError MODIFIER_ERROR A modifier receives bad arguments
RollError RandsumError ROLL_ERROR General roll execution failure
NotationParseError RandsumError INVALID_NOTATION notation() or notationToOptions() rejects a string, or a repeat breaks its limit. Has a suggestion when notation() can infer a fix.
import { roll, RandsumError, ValidationError } from '@randsum/roller'
try {
const result = roll(userInput)
} catch (e) {
if (e instanceof ValidationError) {
// e.context?.notation holds the rejected string
console.error(e.message)
} else if (e instanceof RandsumError) {
console.error(e.code, e.message)
}
}

Every RandsumError carries an optional context property with structured diagnostics. Throw sites populate the fields they know about; consumers can present richer errors (e.g. highlight an invalid character, show which option field failed) without parsing message strings.

interface ErrorContext {
readonly path?: string // dotted path, e.g. 'quantity', 'modifiers.drop.lowest'
readonly value?: unknown // the offending value
readonly notation?: string // the notation string, when relevant
readonly position?: number // zero-indexed character offset in the notation
}

Reading the context:

import { roll, ValidationError, NotationParseError } from '@randsum/roller'
try {
roll({ sides: 6, quantity: -1 })
} catch (e) {
if (e instanceof ValidationError) {
console.error(e.context?.path) // 'quantity'
console.error(e.context?.value) // -1
}
}
try {
roll('1d6x5000') // repeat count exceeds the MAX_REPEAT_COUNT cap
} catch (e) {
if (e instanceof NotationParseError) {
console.error(e.context?.notation) // '1d6x5000'
console.error(e.context?.position) // index of the 'x' operator
}
}

Context is optional and may be undefined, so always use optional chaining (e.context?.path) when reading fields. Not every throw site has path/position information; only use context for display enhancements, not required parsing.

For user-facing inputs such as form fields, chat commands and API parameters, validate before rolling. This avoids try/catch and gives you structured error information.

Returns a structured result with either the validated notation or an error describing what failed.

import { validateNotation, roll } from '@randsum/roller'
function rollUserInput(input: string) {
const validation = validateNotation(input)
if (!validation.valid) {
// validation.error.message describes what's wrong
return { error: validation.error.message }
}
// Safe to roll: validation.argument is typed as DiceNotation
const result = roll(validation.argument)
return { total: result.total }
}

Type guard that narrows a string to DiceNotation. Simpler than validateNotation but gives no error details.

import { isDiceNotation, roll } from '@randsum/roller'
function rollUserInput(input: string) {
if (!isDiceNotation(input)) {
return { error: 'Not valid dice notation' }
}
// input is now typed as DiceNotation
const result = roll(input)
return { total: result.total }
}
console.log(rollUserInput('4d6L'))
console.log(rollUserInput('not-dice'))

isDiceNotation ignores leading and trailing whitespace but, as the spec requires, rejects whitespace between tokens:

Input Valid? Reason
'4d6L' Yes Standard drop-lowest
' 4d6' Yes Leading and trailing whitespace is ignored
'd6' Yes The quantity defaults to 1
'4d6 L' No Whitespace between tokens
'1d20 + 5' No Whitespace between tokens
'4dX' No Non-numeric sides

For cases where you need to catch errors from roll() directly:

import { roll, RandsumError, suggestNotationFix } from '@randsum/roller'
try {
const result = roll(userProvidedNotation)
console.log(result.total)
} catch (e) {
if (e instanceof RandsumError && e.code === 'VALIDATION_ERROR') {
// Offer a fix when one can be inferred
console.error(e.message, suggestNotationFix(userProvidedNotation))
} else if (e instanceof RandsumError) {
console.error(e.code, e.message)
} else {
throw e // Re-throw unexpected errors
}
}

RANDSUM’s types are written for exactOptionalPropertyTypes. If your tsconfig.json enables it, setting an optional field of ModifierOptions to undefined fails to compile.

import type { ModifierOptions } from '@randsum/roller'
// This fails under exactOptionalPropertyTypes:
const mods: ModifierOptions = {
drop: { lowest: undefined } // 'undefined' is not assignable to 'number'
}
// Correct: set a value, or omit the key entirely
const mods: ModifierOptions = {
drop: { lowest: 1 }
}

Always import types from @randsum/roller rather than constructing them inline without annotations. This lets TypeScript catch shape mismatches at the point of definition.

import type { RollOptions, ModifierOptions } from '@randsum/roller'
const options: RollOptions = {
sides: 6,
quantity: 4,
modifiers: {
drop: { lowest: 1 }
}
}

If notation parses but gives unexpected results, modifier execution order is usually the cause. Modifiers run in a fixed priority order, lowest number first. For example, cap (priority 10) runs before drop (priority 65).

import { roll } from '@randsum/roller'
// cap runs first, then drop
const result = roll('4d6C{<2}L')
console.log(result.rolls) // Inspect per-group roll details
console.log(result.total)

See the Modifiers reference for the complete execution order.

  • Notation in your code: no error handling needed; roll('2d6') never throws
  • User-provided notation: validate with validateNotation() or isDiceNotation() before calling roll()
  • Dynamic options objects: validate inputs before constructing options, or wrap in try/catch
  • Game packages: their roll() functions also throw on invalid input, so validate at the boundary

Open an issue on GitHub with the input you passed to roll(), the full error message, and your @randsum/roller version.