Errors
Catch Active Record’s errors, and see when each one is thrown.
At a glance
| To | Check |
|---|---|
| tell Active Record’s errors from any other | error instanceof ActiveRecordError |
| 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 active-record schema generates:
import { ApplicationRecord } from "./application-record";
// No uniqueness validation: the table's UNIQUE index refuses a taken email.
export class User extends ApplicationRecord {}// Generated by `active-record schema` from migrations/ — don't edit.
// schema: 29e48056c30c
import { defineSchema, type TableAttributes } from "@forestfuture/active-record";
import { d1 } from "@forestfuture/active-record/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"]> {}
}CREATE TABLE users (
id TEXT PRIMARY KEY NOT NULL,
email TEXT NOT NULL
);
CREATE UNIQUE INDEX index_users_on_email ON users (email);CREATE TABLE users (
id UUID PRIMARY KEY,
email TEXT NOT NULL
);
CREATE UNIQUE INDEX index_users_on_email ON users (email);Checking for Active Record’s errors
Every error Active Record throws extends ActiveRecordError, so one check separates them from anything else:
import { class ActiveRecordErrorBase class for every error the library throws on purpose.ActiveRecordError, class RecordNotFoundNo record matched a lookup that requires one (`find`, `findByOrThrow`, `sole`).RecordNotFound } from "@forestfuture/active-record";
import { class UserUser } from "./models/user";
export async function function showUser(id: string): Promise<Response>showUser(id: stringid: string): interface Promise<T>Represents the completion of an asynchronous operationPromise<Response> {
try {
return var Response: {
new (body?: BodyInit | null, init?: ResponseInit): Response;
prototype: Response;
error(): Response;
json(data: any, init?: ResponseInit): Response;
redirect(url: string | URL, status?: number): Response;
}
The **`Response`** interface of the Fetch API represents the response to a request.
[MDN Reference](https://developer.mozilla.org/docs/Web/API/Response)Response.function json(data: any, init?: ResponseInit): ResponseThe **`json()`** static method of the Response interface returns a Response that contains the provided JSON data as body, and a Content-Type header which is set to application/json. The response status, status message, and additional headers can also be set.
[MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/json_static)json(await class UserUser.OverloadedStatics.find: <typeof User>(this: typeof User, id: string | number) => Promise<User> (+2 overloads)find(id: stringid));
} catch (function (local var) error: unknownerror) {
if (function (local var) error: unknownerror instanceof class RecordNotFoundNo record matched a lookup that requires one (`find`, `findByOrThrow`, `sole`).RecordNotFound) return new var Response: new (body?: BodyInit | null, init?: ResponseInit) => ResponseThe **`Response`** interface of the Fetch API represents the response to a request.
[MDN Reference](https://developer.mozilla.org/docs/Web/API/Response)Response("No such user", { ResponseInit.status?: number | undefinedstatus: 404 });
if (function (local var) error: unknownerror instanceof class ActiveRecordErrorBase class for every error the library throws on purpose.ActiveRecordError) return new var Response: new (body?: BodyInit | null, init?: ResponseInit) => ResponseThe **`Response`** interface of the Fetch API represents the response to a request.
[MDN Reference](https://developer.mozilla.org/docs/Web/API/Response)Response(function (local var) error: ActiveRecordErrorerror.Error.message: stringmessage, { ResponseInit.status?: number | undefinedstatus: 400 });
throw function (local var) error: unknownerror; // not one of Active Record'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 |
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 |
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 sameselect, order,limit,offset,distinct, andincludes, since only their conditions can be combined.batch,db.batch,save(), ordestroy()with writes or records on two databases, such as abelongsTotarget built on anotherconnect(). A write runs on one database. The message names where each database came from. A batch also refuses a record whose autosave ordependentstrategies reach an association to another database.includeswithselect(...).distinct(). Preloading needs the keys, and adding them would undo thedistinct.- Preloading an association scope that uses
limit,offset, ordistinct. One preload query serves every owner, so the limit would apply to all of their records together. updateAllordeleteAllafterdistinct(): they reject with it, and so does a batch preparing them.
Constraint errors
When the database refuses a write because of a constraint, Active Record 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:
import { class RecordNotUniqueA UNIQUE constraint failed, e.g. another request won the race after validation passed.RecordNotUnique } from "@forestfuture/active-record";
import { class UserUser } from "./models/user";
export async function function signUp(email: string): Promise<User>signUp(email: stringemail: string) {
const const user: Useruser = class UserUser.build<typeof User>(this: typeof User, attributes?: Partial<AttributeProperties<OverriddenSpecs<{
readonly id: {
readonly type: "string";
readonly null: false;
readonly generateId: true;
};
readonly email: {
readonly type: "string";
readonly null: false;
};
}, Readonly<Record<string, false | AttributeOverride>> | undefined>>> | undefined, init?: ((record: User) => void) | undefined): User
A new, unsaved record of this Relation's Model, handed to `init` first if it's given. Nothing
awaits `init`, so one that returns a promise throws `TypeError`. Built through a hasMany, it
joins the association, and saving the owner saves it too (autosave).build({ email?: string | undefinedemail });
try {
await const user: Useruser.Model.save(options?: SaveOptions): Promise<boolean>Inserts a new record or updates a persisted one; `false` if it's invalid, a callback aborted,
or a record it destroys refused (#37). `context` validates it in that context (`"signup"`), as
`isValid(context)` does.save();
} catch (function (local var) error: unknownerror) {
if (function (local var) error: unknownerror instanceof class RecordNotUniqueA UNIQUE constraint failed, e.g. another request won the race after validation passed.RecordNotUnique && function (local var) error: RecordNotUniqueerror.ConstraintViolation.attributes: readonly string[]attributes.ReadonlyArray<string>.includes(searchElement: string, fromIndex?: number): booleanDetermines whether an array includes a certain element, returning true or false as appropriate.includes("email")) {
const user: Useruser.Model.errors: ErrorsThe errors from the last validation run.errors.Errors.add(attribute: string, message: string, options?: {
type?: string;
}): void (+1 overload)
Adds an error with this message; `type` defaults to `"invalid"`. Use `"base"` for the
record as a whole.add("email", "has already been taken", { type?: string | undefinedtype: "taken" });
} else {
throw function (local var) error: unknownerror;
}
}
return const user: Useruser;
}Every method throws them, save() as well as saveOrThrow(). The record keeps its changes, so you can fix them and save again.