The failure table from the last lesson gives every failure on the wall’s API a status and a stable code. Ines’s new rule adds a row your code can’t send yet. Two problems must never share a name, so a second Chalk Dust gets a 409 with problem_exists.
Only the store can spot that duplicate, because only the store holds every problem. However, the store knows nothing about HTTP, and it should stay that way.
In this lesson, you’ll give the store errors of its own, add an error class for the failures only the HTTP layer can name, and write one function that turns any error into a row of the table.
Give the Store Errors of Its Own
The store can only report a failure through its return value today. When store.get() can’t find an ID, it returns undefined, and every handler that calls it has to check for that and build the 404 itself. A duplicate name doesn’t fit that pattern at all, since store.create() returns the new problem.
Instead, the store can throw an error that says what went wrong. A custom error class extends Error and sets its own .name, so the code that catches it can tell it apart from every other error.
A missing problem is a domain error. It describes a failure in the API’s own terms—problems and their names—with no status code in sight. Create a file called errors.ts next to store.ts and add these two error classes:
errors.ts
export class NotFoundError extends Error {
resource: string;
constructor(resource: string, id: string) {
super(`No ${resource} with id ${id}.`);
this.name = "NotFoundError";
this.resource = resource;
}
}
export class ConflictError extends Error {
resource: string;
constructor(resource: string, message: string) {
super(message);
this.name = "ConflictError";
this.resource = resource;
}
}
Each class keeps the kind of record it’s about in .resource, such as "problem", so the same two classes serve any store. You declare the fields at the top of the class and set them in the constructor because the project’s erasableSyntaxOnly setting rules out TypeScript’s shorthand that declares a field in the constructor’s parameter list.
Now the store needs to know what its records are called and which field must be unique. In store.ts, import the errors and give createStore() an optional second parameter:
store.ts
import { readFile, rename, writeFile } from "node:fs/promises";
import { ConflictError, NotFoundError } from "./errors.ts";
type StoreOptions<T> = {
name?: string;
unique?: keyof T & string;
};
export async function createStore<T extends { id: string }>(
file: string,
{ name = "record", unique }: StoreOptions<T> = {},
) {
// ...
keyof T & string limits unique to the names of the record’s fields, so TypeScript refuses a typo such as "nmae". The climbing log’s store passes no options, so it skips uniqueness checks, but missing IDs now throw NotFoundError.
Below save(), add two helpers, one for each failure:
store.ts
function indexOf(id: string): number {
const index = records.findIndex((record) => record.id === id);
if (index === -1) {
throw new NotFoundError(name, id);
}
return index;
}
function checkUnique(record: T) {
if (unique === undefined) {
return;
}
const value = record[unique];
const clash = records.some(
(other) => other.id !== record.id && other[unique] === value,
);
if (clash) {
const message = `A ${name} with ${unique} ${value} already exists.`;
throw new ConflictError(name, message);
}
}
checkUnique() skips the record’s own ID, so a PATCH that sends a problem’s current name back doesn’t clash with itself. The comparison is exact, so a new problem called chalk dust would still get in next to Chalk Dust. A real rule would compare a normalized form of each name, such as its lowercase version.