Sub topic 2
Building an Error Hierarchy
This chapter assumes you can write a basic custom error class that calls super(message, options) and sets this.name. It also assumes you know try/catch and async/await.
Building an Error Hierarchy
An error hierarchy is a set of error classes where general classes sit at the top and specific ones extend them. The base class holds the shared fields. Each subclass fixes those fields and builds its own message.
class HttpError extends Error {
constructor(status, message, options) {
super(message, options);
this.name = 'HttpError';
this.status = status;
}
}
class NotFoundError extends HttpError {
constructor(resource, options) {
super(404, `${resource} not found`, options);
this.name = 'NotFoundError';
}
}
const err = new NotFoundError('User 42');
console.log(err.status); // 404
console.log(err instanceof HttpError); // true
console.log(err.message); // 'User 42 not found'Catching Errors Selectively with instanceof
A subclass instance also passes instanceof for every class above it. Because of that, check the most specific class first. Rethrow anything you don't recognize so that unexpected bugs are not silently swallowed.
function handle(fn) {
try {
fn();
} catch (err) {
if (err instanceof NotFoundError) {
console.warn(err.message);
} else if (err instanceof HttpError) {
console.error(`Request failed with status ${err.status}`);
} else {
throw err;
}
}
}
handle(() => { throw new NotFoundError('User 42'); });
handle(() => { throw new HttpError(503, 'Unavailable'); });If the HttpError check came first, it would also catch every NotFoundError, and the NotFoundError branch would never run.
Attaching the Original Error with cause
Since ES2022, the Error constructor accepts a second argument, { cause }. The value is stored on err.cause. Your subclasses keep this feature only if they pass options on to super.
Wrapping Errors at Layer Boundaries
Low-level errors such as ENOENT or Unexpected token don't say what the program was trying to do. Catch them at the edge of a layer, throw a higher-level error that names the operation that failed, and attach the original error as the cause.
import { readFile } from 'node:fs/promises';
async function loadConfig(path) {
try {
const text = await readFile(path, 'utf8');
return JSON.parse(text);
} catch (err) {
throw new Error(`Failed to load config from ${path}`, { cause: err });
}
}
try {
await loadConfig('./missing.json');
} catch (err) {
console.log(err.message); // 'Failed to load config from ./missing.json'
console.log(err.cause.code); // 'ENOENT'
}Exercise
A catch block checks err instanceof HttpError before err instanceof NotFoundError. What happens when a NotFoundError is thrown, and how do you fix it?
Show answer
The HttpError branch handles it, because a NotFoundError is also an HttpError, so the NotFoundError branch never runs. Fix it by putting the more specific NotFoundError check first.