# 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.

## When `roll()` throws

`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.

## Error hierarchy

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. |

<CodeExample code={`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)
  }
}`} />

## Structured error context

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.

```ts
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:

<CodeExample code={`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.

## Validate before rolling

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.

### `validateNotation`

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

<CodeExample code={`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 }
}`} />

<NotationRoller defaultNotation="4d6L" />

### `isDiceNotation`

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

<CodeExample code={`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](https://notation.randsum.dev/) 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 |

**Tip:** `suggestNotationFix()` from `@randsum/roller` can correct common mistakes, such as stray spaces (`'4d6 L'` → `'4d6L'`). `notation()` puts its result in the `suggestion` of the `NotationParseError` it throws. See [Validation & Parsing](https://randsum.dev/notation/validation-and-parsing/) for details.

## Try/catch

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

<CodeExample code={`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
  }
}`} />

## Common TypeScript issues

### `exactOptionalPropertyTypes`

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

<CodeExample code={`// 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 }
}`} />

### Import types directly

Always const options: RollOptions = {
  sides: 6,
  quantity: 4,
  modifiers: {
    drop: { lowest: 1 }
  }
}`} />

## Modifier execution order

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).

<CodeExample code={`// 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](https://randsum.dev/roller/modifiers/) reference for the complete execution order.

## Production checklist

- **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

## Still stuck?

[Open an issue on GitHub](https://github.com/RANDSUM/randsum/issues) with the input you passed to `roll()`, the full error message, and your `@randsum/roller` version.