Typed Error Classes and Hierarchies
Create custom error classes with discriminated types.
Typed Error Classes and Hierarchies is a free TypeScript Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the TypeScript Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Welcome
Extending Error
class AppError extends Error {
constructor(public message: string, public statusCode = 500) {
super(message);
this.name = 'AppError';
}
}Error Hierarchy
class NotFoundError extends AppError {
constructor(resource: string) { super(`${resource} not found`, 404); }
}
class ValidationError extends AppError {
constructor(public fields: string[]) { super('Validation failed', 400); }
}Using instanceof
try { doSomething(); }
catch (err) {
if (err instanceof NotFoundError) res.status(404).json({ error: err.message });
else if (err instanceof ValidationError) res.status(400).json({ fields: err.fields });
}Discriminated Error Union
type AppError =
| { kind: 'not_found'; resource: string }
| { kind: 'unauthorized' }
| { kind: 'validation'; fields: string[] };Error Factory Functions
const errors = {
notFound: (r: string) => new NotFoundError(r),
unauthorized: () => new AppError('Unauthorized', 401),
};Error Serialization
function serializeError(err: AppError): Record<string, unknown> {
return { error: err.message, code: err.statusCode, name: err.name };
}Setting this.name
class MyError extends Error {
readonly name = 'MyError' as const;
constructor(msg: string) { super(msg); }
}Error in Express
app.use((err: unknown, req: Request, res: Response, next: NextFunction) => {
if (err instanceof AppError) {
res.status(err.statusCode).json({ error: err.message });
} else {
res.status(500).json({ error: 'Internal error' });
}
});Error Logging Pattern
function logError(err: unknown): void {
if (err instanceof Error) console.error(`[${err.name}] ${err.message}`);
else console.error('Unknown error:', err);
}Testing Error Types
test('throws NotFoundError for missing user', async () => {
await expect(getUser(999)).rejects.toThrow(NotFoundError);
});Quick Check
Recap
Frequently asked questions
Is the “Typed Error Classes and Hierarchies” lesson free?
Yes — the full text of “Typed Error Classes and Hierarchies” is free to read here on the web, and the TypeScript Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the TypeScript Academy course, upgrade to CoddyKit PRO.
What will I learn in “Typed Error Classes and Hierarchies”?
Create custom error classes with discriminated types. You practise TypeScript Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start TypeScript Academy?
No prior experience is required. TypeScript Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Typed Error Classes and Hierarchies” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this TypeScript Academy lesson?
Yes. Every TypeScript Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Typed Error Classes and Hierarchies
- The Result Pattern: Ok and Err
- Narrowing Caught Errors (unknown vs Error)
- Error Handling in Async TypeScript Code