# Errors

> Reference for RecipeBookError, RecipeValidationError, isRecipeBookError, isRecipeValidationError, RecipeIssue, and the error and issue codes.

Source: https://recipe-book.siraj.page/reference/core/errors/

Use these exports to catch and identify the errors Recipe Book throws, and to read the issues it reports for recipe input and for the recipe and options passed to [`toJsonLd`](https://recipe-book.siraj.page/reference/core/schema-org.md#tojsonld). In a React app, replace `@recipe-book/core` with `@recipe-book/react/core` in this page's imports.

Recipe Book throws a [`RecipeBookError`](https://recipe-book.siraj.page/reference/core/errors.md#recipebookerror) for the mistakes it checks, such as converting cups to grams, with a message that says how to fix the call. Problems in recipe input are [`RecipeIssue`](https://recipe-book.siraj.page/reference/core/errors.md#recipeissue) values instead, which [`parseRecipe`](https://recipe-book.siraj.page/reference/core/parsing.md#parserecipe), [`parseQuantity`](https://recipe-book.siraj.page/reference/core/parsing.md#parsequantity), [`parseIngredientLine`](https://recipe-book.siraj.page/reference/core/parsing.md#parseingredientline), and [`fromJsonLd`](https://recipe-book.siraj.page/reference/core/schema-org.md#fromjsonld) return in a [`RecipeValidationError`](https://recipe-book.siraj.page/reference/core/errors.md#recipevalidationerror) rather than throw, so bad input never crashes a page. [`toJsonLd`](https://recipe-book.siraj.page/reference/core/schema-org.md#tojsonld) returns `RecipeIssue` warnings too, for what the JSON-LD it writes lacks, for a time it leaves out because it's too long or `NaN`, and for the options it ignores.

[`resolveRecipe`](https://recipe-book.siraj.page/reference/core/resolving.md#resolverecipe) and [`toJsonLd`](https://recipe-book.siraj.page/reference/core/schema-org.md#tojsonld) don't check that their recipe was parsed, so passing the parse result itself, as in `resolveRecipe(result)` rather than `resolveRecipe(result.data)`, throws a `TypeError`, not a `RecipeBookError`.

## `RecipeBookError`

```ts
class RecipeBookError extends Error {
  readonly name: 'RecipeBookError' | 'RecipeValidationError'
  readonly code: RecipeBookErrorCode
  readonly docsUrl: `https://recipe-book.siraj.page/errors/${RecipeBookErrorCode}/`
  constructor(
    code: RecipeBookErrorCode,
    message: string,
    options?: { cause?: unknown },
  )
}
```

The error Recipe Book throws for the mistakes it checks, with a stable code and a link to the page that explains the fix.

| Name      | Type                                                                                                 | Default  | Description                                                  |
| --------- | ---------------------------------------------------------------------------------------------------- | -------- | ------------------------------------------------------------ |
| `code`    | [`RecipeBookErrorCode`](https://recipe-book.siraj.page/reference/core/errors.md#recipebookerrorcode) | Required | The code that names the problem.                             |
| `message` | `string`                                                                                             | Required | What went wrong and how to fix it.                           |
| `options` | `{ cause?: unknown }`                                                                                | None     | The error that caused this one, as for the built-in `Error`. |

Each instance has these properties:

| Name      | Type                                                                                                 | Description                                                                                         |
| --------- | ---------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- |
| `name`    | `'RecipeBookError' \| 'RecipeValidationError'`                                                       | `'RecipeBookError'`, or `'RecipeValidationError'` for the subclass.                                 |
| `code`    | [`RecipeBookErrorCode`](https://recipe-book.siraj.page/reference/core/errors.md#recipebookerrorcode) | The code that names the problem. Branch on `code` rather than on `message`.                         |
| `docsUrl` | `` `https://recipe-book.siraj.page/errors/${RecipeBookErrorCode}/` ``                                | The page for the code.                                                                              |
| `message` | `string`                                                                                             | The message passed to the constructor, followed by a line that links to `docsUrl`: `See <docsUrl>`. |

```ts
import { convert, isRecipeBookError } from '@recipe-book/core'

try {
  convert({ amount: 1.5, unit: 'cup' }, 'g')
} catch (error) {
  if (!isRecipeBookError(error)) throw error
  error.code // 'incompatible_units'
  error.docsUrl // 'https://recipe-book.siraj.page/errors/incompatible_units/'
}
```

## `RecipeValidationError`

```ts
class RecipeValidationError extends RecipeBookError {
  readonly name: 'RecipeValidationError'
  readonly code: ValidationErrorCode
  readonly issues: readonly RecipeIssue[]
  constructor(
    code: ValidationErrorCode,
    issues: readonly RecipeIssue[],
    subject?: string,
  )
}
```

A [`RecipeBookError`](https://recipe-book.siraj.page/reference/core/errors.md#recipebookerror) that collects every problem found in recipe input, quantity text, or an ingredient line.

| Name      | Type                                                                                                 | Default                                                                                                       | Description                                                                                                                                                                                                                                                                              |
| --------- | ---------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `code`    | [`ValidationErrorCode`](https://recipe-book.siraj.page/reference/core/errors.md#validationerrorcode) | Required                                                                                                      | `'invalid_recipe'` for a recipe, `'invalid_quantity'` for a single quantity, or `'invalid_ingredient'` for an ingredient line.                                                                                                                                                           |
| `issues`  | readonly [`RecipeIssue`](https://recipe-book.siraj.page/reference/core/errors.md#recipeissue)[]      | Required                                                                                                      | The issues to report, of either severity.                                                                                                                                                                                                                                                |
| `subject` | `string`                                                                                             | `'Recipe'` for `invalid_recipe`, `'Quantity'` for `invalid_quantity`, `'Ingredient'` for `invalid_ingredient` | What was validated, shown as given at the start of the message. Recipe Book's own errors quote the recipe's name or the input text like a JSON string, cut with "…" when longer than 60 UTF-16 code units, or use the default when the recipe has no valid name or the input isn't text. |

The message counts the issues and lists each one on its own line: ✖ for severity `'error'` or ⚠ for `'warning'`, then the path and the issue's message. It lists the first 10 issues, then a line such as `…and 2 more. error.issues lists them all.`, so it stays readable in logs. [Validate recipes](https://recipe-book.siraj.page/guides/validate-recipes.md#read-issues) shows a full message.

```ts
import { parseRecipe } from '@recipe-book/core'

const result = parseRecipe({
  name: 'Buttermilk pancakes',
  serving: 4,
  ingredients: [
    { name: 'all-purpose flour', quantity: '1 ½ cupz', equivalents: ['190 g'] },
    { name: 'egg', plural: 'eggs', quantity: 0 },
  ],
  steps: ['Whisk the dry ingredients.', 'Fold in the wet ingredients.'],
})

if (!result.success) {
  result.error.code // 'invalid_recipe'
  result.error.issues.length // 3
}
```

[`invalid_recipe`](https://recipe-book.siraj.page/errors/invalid_recipe.md), [`invalid_quantity`](https://recipe-book.siraj.page/errors/invalid_quantity.md), and [`invalid_ingredient`](https://recipe-book.siraj.page/errors/invalid_ingredient.md) each show a message and explain how to read and fix its issues.

## `ValidationErrorCode`

```ts
type ValidationErrorCode =
  'invalid_recipe' | 'invalid_quantity' | 'invalid_ingredient'
```

The codes a [`RecipeValidationError`](https://recipe-book.siraj.page/reference/core/errors.md#recipevalidationerror) can carry, one for each `parse*` function. The union may grow in minor releases.

## `isRecipeBookError`

```ts
function isRecipeBookError(error: unknown): error is RecipeBookError
```

Checks whether a value is a Recipe Book error, from any copy of `@recipe-book/core`.

| Name    | Type      | Default  | Description                                 |
| ------- | --------- | -------- | ------------------------------------------- |
| `error` | `unknown` | Required | The value to check, usually a caught error. |

Returns `true` when `error` is an object whose `name` is `'RecipeBookError'` or `'RecipeValidationError'` and whose `code` is a [`RecipeBookErrorCode`](https://recipe-book.siraj.page/reference/core/errors.md#recipebookerrorcode), and narrows its type to [`RecipeBookError`](https://recipe-book.siraj.page/reference/core/errors.md#recipebookerror).

```ts
import { isRecipeBookError } from '@recipe-book/core'

isRecipeBookError(new Error('Network error')) // false
```

Use it rather than `instanceof RecipeBookError`. An app can load two copies of `@recipe-book/core`, such as two versions, or the ESM and CommonJS builds of one version, and `instanceof` returns `false` for errors from the other copy.

Never throws.

## `isRecipeValidationError`

```ts
function isRecipeValidationError(error: unknown): error is RecipeValidationError
```

Checks whether a value is a [`RecipeValidationError`](https://recipe-book.siraj.page/reference/core/errors.md#recipevalidationerror), from any copy of `@recipe-book/core`, so you can read its `issues`.

| Name    | Type      | Default  | Description                                 |
| ------- | --------- | -------- | ------------------------------------------- |
| `error` | `unknown` | Required | The value to check, usually a caught error. |

Returns `true` when `error` is an object whose `name` is `'RecipeValidationError'`, whose `code` is a [`ValidationErrorCode`](https://recipe-book.siraj.page/reference/core/errors.md#validationerrorcode), and whose `issues` is an array, and narrows its type to `RecipeValidationError`.

```ts
import { isRecipeValidationError, parseRecipe } from '@recipe-book/core'

try {
  const result = parseRecipe({ name: 'Toast', servings: 0 })
  if (!result.success) throw result.error
} catch (error) {
  if (isRecipeValidationError(error)) {
    error.issues[0] // { code: 'invalid_amount', severity: 'error', path: ['servings'], message: 'Expected a positive number, received 0.' }
  }
}
```

Use it rather than `instanceof RecipeValidationError`, for the same reason as [`isRecipeBookError`](https://recipe-book.siraj.page/reference/core/errors.md#isrecipebookerror).

Never throws.

## `RecipeBookErrorCode`

```ts
type RecipeBookErrorCode =
  | 'invalid_recipe'
  | 'invalid_quantity'
  | 'invalid_ingredient'
  | 'invalid_argument'
  | 'incompatible_units'
  | 'unknown_unit'
  | 'missing_parent'
```

The codes a [`RecipeBookError`](https://recipe-book.siraj.page/reference/core/errors.md#recipebookerror) can carry. [Error codes](https://recipe-book.siraj.page/errors.md) explains each one and links to its page. The union may grow in minor releases, so give code that branches on it a default case.

## `RecipeIssue`

```ts
type RecipeIssue = {
  code: RecipeIssueCode
  severity: 'error' | 'warning'
  path: readonly (string | number)[]
  message: string
  suggestion?: string | undefined
}
```

A problem found in recipe input, quantity text, an ingredient line, or the recipe and options passed to `toJsonLd`, reported as a value rather than thrown.

| Name         | Type                                                                                         | Description                                                                                                                                                                                                                                        |
| ------------ | -------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `code`       | [`RecipeIssueCode`](https://recipe-book.siraj.page/reference/core/errors.md#recipeissuecode) | The kind of problem.                                                                                                                                                                                                                               |
| `severity`   | `'error' \| 'warning'`                                                                       | `'error'` when the problem fails the parse, or `'warning'` when it doesn't. A successful parse returns its warnings in `warnings`; a failed one keeps them in `error.issues`, with the errors.                                                     |
| `path`       | `readonly (string \| number)[]`                                                              | Where the problem is in the input, such as `['ingredients', 0, 'quantity']`. From `toJsonLd`, it's the schema.org name of what the JSON-LD lacks, such as `['image']`, or a path in the recipe or in `options`, such as `['options', 'servings']`. |
| `message`    | `string`                                                                                     | Text to show the author as it is. An error's message names the fix; a warning's may only describe the problem, such as `'Recipe has no steps.'`.                                                                                                   |
| `suggestion` | `string \| undefined`                                                                        | The value the input most likely meant, for "did you mean" hints, such as `'cups'`.                                                                                                                                                                 |

[Validate recipes](https://recipe-book.siraj.page/guides/validate-recipes.md#validate-a-form) shows how to match an issue's `path` to a form field.

```ts
import { parseQuantity } from '@recipe-book/core'

const result = parseQuantity('2 cupz')

if (!result.success) {
  result.error.issues // [{ code: 'unknown_unit', severity: 'error', path: [], message: 'Unknown unit "cupz". Did you mean "cups"?', suggestion: 'cups' }]
}
```

## `RecipeIssueCode`

```ts
type RecipeIssueCode =
  | 'invalid_type'
  | 'missing_field'
  | 'unknown_unit'
  | 'invalid_quantity'
  | 'invalid_amount'
  | 'invalid_range'
  | 'invalid_duration'
  | 'invalid_url'
  | 'unknown_field'
  | 'duplicate_id'
  | 'empty_list'
  | 'ignored_value'
```

The kinds of problem a [`RecipeIssue`](https://recipe-book.siraj.page/reference/core/errors.md#recipeissue) can report. [Issue codes](https://recipe-book.siraj.page/errors.md#issue-codes) explains each one, its severity, and its fix. The union may grow in minor releases.
