---
title: Errors
description: "Catch Arbor’s errors, and see when each one is thrown."
seo:
  description: "Every error Arbor throws, from RecordNotFound and RecordInvalid to constraint errors, how to catch them with ArborError, and when each is thrown."
---

## At a glance

| To                                  | Check                                                       |
| ----------------------------------- | ----------------------------------------------------------- |
| tell Arbor’s errors from any other  | `error instanceof ArborError`                               |
| return a 404 for a missing record   | `error instanceof RecordNotFound`                           |
| read why an `OrThrow` save failed   | `error instanceof RecordInvalid`, then `error.record`       |
| catch a duplicate the table refused | `error instanceof RecordNotUnique`, then `error.attributes` |

## The Models

The examples use this Model, whose attributes come from its table through the schema `arbor schema` generates:

```ts user.ts
import { ApplicationRecord } from "./application-record";

// No uniqueness validation: the table's UNIQUE index refuses a taken email.
export class User extends ApplicationRecord {}
```

```ts schema.ts
// Generated by `arbor schema` from migrations/ — don't edit.
// schema: 6a307df1cd77

import { defineSchema, type TableAttributes } from "@forestfuture/arbor";
import { d1 } from "@forestfuture/arbor/d1";

/** users — last changed by 0001_create_tables.sql */
export const users = {
  id: { type: "string", null: false, generateId: true },
  email: { type: "string", null: false },
} as const;

/** The database's adapter and binding, its tables (with their primary keys), and the Models built on them. */
export const schema = defineSchema({
  adapter: d1({ binding: "DB" }),
  tables: {
    users: { attributes: users, primaryKey: "id" },
  },
  models: { User: "users" },
});

declare module "../models/user" {
  interface User extends TableAttributes<typeof users, (typeof User)["attributes"]> {}
}
```

```sql D1
CREATE TABLE users (
  id TEXT PRIMARY KEY NOT NULL,
  email TEXT NOT NULL
);
CREATE UNIQUE INDEX index_users_on_email ON users (email);
```

```sql Postgres
CREATE TABLE users (
  id UUID PRIMARY KEY,
  email TEXT NOT NULL
);
CREATE UNIQUE INDEX index_users_on_email ON users (email);
```

## Checking for Arbor’s errors

Every error Arbor throws extends `ArborError`, so one check separates them from anything else:

```ts
import { ArborError, RecordNotFound } from "@forestfuture/arbor";
import { User } from "./models/user";

export async function showUser(id: string): Promise<Response> {
  try {
    return Response.json(await User.find(id));
  } catch (error) {
    if (error instanceof RecordNotFound) return new Response("No such user", { status: 404 });
    if (error instanceof ArborError) return new Response(error.message, { status: 400 });
    throw error; // not one of Arbor's own
  }
}
```

## Lifecycle errors

| Error                   | When                                                                                        |
| ----------------------- | ------------------------------------------------------------------------------------------- |
| `RecordNotFound`        | `find`, `sole`, an `OrThrow` finder, or `reload` found nothing                              |
| `SoleRecordExceeded`    | `sole` or `findSoleBy` found more than one record                                           |
| `RecordInvalid`         | an `OrThrow` save found the record invalid; the record is on `.record`                      |
| `RecordNotSaved`        | a save was aborted by a callback, or needs an owner that isn’t saved                        |
| `RecordNotDestroyed`    | a destroy was aborted, or restricted by `restrictWithError`                                 |
| `RecordDestroyed`       | writing to a record that’s already destroyed                                                |
| `StaleRecord`           | a [locked](/optimistic-locking) record’s row changed since it was loaded                   |
| `ReadonlyRecord`        | writing a [read-only](/read-only) record; what was refused is on `.action`                 |
| `ReadonlyAttribute`     | changing a saved record’s [read-only](/read-only#declaring-read-only-attributes) attribute |
| `CallbackAbort`         | what `abort()` makes; caught by the lifecycle                                               |
| `AbortAfterPersistence` | `abort()` in an after-callback, too late to stop the write (`.callback`)                    |

## Usage errors

A usage error means the code needs to change:

| Error                  | When                                                                            |
| ---------------------- | ------------------------------------------------------------------------------- |
| `InvalidModel`         | a Model’s declaration is wrong, detected the first time it’s used               |
| `UnknownAttribute`     | an attribute that isn’t declared, in `build`, `where`, `update`, …              |
| `MissingAttribute`     | reading an attribute that `select` didn’t load                                  |
| `UnknownAssociation`   | an association that isn’t declared                                              |
| `AssociationNotLoaded` | `loaded()` on an association that wasn’t loaded                                 |
| `UnknownModelName`     | a polymorphic association’s stored type that names none of the Models it lists  |
| `IncompatibleRelation` | two Relations or writes can’t be used together (below)                          |
| `IrreversibleOrder`    | `last()` on a Relation ordered by an `sql` fragment                             |
| `DeleteRestriction`    | destroying an owner whose `restrictWithException` association still has records |
| `NoDatabase`           | using a record made with `new` rather than `build`                              |
| `NoSession`            | `db.bookmark()` on a Database opened without a session                          |

:::note
A name from a request, such as `?include=` or a JSON key, only ever matches the Model’s own attributes and associations; `constructor` and `__proto__` are unknown like any other. Return a 400 for these errors.
:::

### When Relations are incompatible

`IncompatibleRelation` is thrown for combinations that can’t make a correct query or write:

- **`or()`, `merge()`, or a scope** with a Relation of another Model, or one that resolves to another database when it runs. `or()` also needs both sides to have the same `select`, order, `limit`, `offset`, `distinct`, and `includes`, since only their conditions can be combined.
- **`batch`, `db.batch`, `save()`, or `destroy()`** with writes or records on two databases, such as a `belongsTo` target built on another `connect()`. A write runs on one database. The message names where each database came from. A batch also refuses a record whose autosave or `dependent` strategies reach an association to [another database](/several-databases#associating-models-on-different-databases).
- **`includes`** with `select(...).distinct()`. Preloading needs the keys, and adding them would undo the `distinct`.
- **Preloading an association scope** that uses `limit`, `offset`, or `distinct`. One preload query serves every owner, so the limit would apply to all of their records together.
- **`updateAll` or `deleteAll`** after `distinct()`: they reject with it, and so does a batch preparing them.

## Constraint errors

When the database refuses a write because of a constraint, Arbor throws a subclass of `ConstraintViolation`:

| Error               | Constraint              |
| ------------------- | ----------------------- |
| `RecordNotUnique`   | `UNIQUE`, `PRIMARY KEY` |
| `InvalidForeignKey` | `FOREIGN KEY`           |
| `NotNullViolation`  | `NOT NULL`              |
| `CheckViolation`    | `CHECK`                 |

Each has the database’s original error as `cause`, the `table`, and, where the database’s message names them, the `columns` and `attributes`. `User` has no uniqueness validation, so its UNIQUE index refuses a taken email:

```ts
import { RecordNotUnique } from "@forestfuture/arbor";
import { User } from "./models/user";

export async function signUp(email: string) {
  const user = User.build({ email });
  try {
    await user.save();
  } catch (error) {
    if (error instanceof RecordNotUnique && error.attributes.includes("email")) {
      user.errors.add("email", "has already been taken", { type: "taken" });
    } else {
      throw error;
    }
  }
  return user;
}
```

Every method throws them, `save()` as well as `saveOrThrow()`. The record keeps its changes, so you can fix them and save again.
