Custom errors
Overview
A single Error type can’t tell callers what went wrong. Was the input invalid? Was the record missing? Did the network fail? Checking the message text (if (error.message.includes('not found'))) is fragile — someone rewords the message and your code breaks.
Custom error classes solve this. Each kind of problem gets its own type, and callers check the type:
class ValidationError extends Error {
constructor(field, message) {
super(message);
this.name = 'ValidationError';
this.field = field;
}
}Anatomy of a custom error
class ValidationError extends Error {
constructor(field, message) {
super(message); // 1. let Error set up message and stack
this.name = 'ValidationError'; // 2. shows in the console and error.name
this.field = field; // 3. any extra information callers need
}
}super(message)runs the built-inErrorconstructor, which setsmessageand captures the stack trace.nameis what the console prints before the message:ValidationError: Please enter…. Without it, it would just sayError.- Extra properties carry details that help the caller respond — which field, which id, which HTTP status.
A neat trick avoids typing the name twice: this.name = this.constructor.name; (or declare it as a class field: name = 'ValidationError';).
Throwing and handling them
function saveProfile(profile) {
if (!profile.email.includes('@')) {
throw new ValidationError('email', 'Please enter a valid email address.');
}
// …save
}
try {
saveProfile({ email: 'asha' });
} catch (error) {
if (error instanceof ValidationError) {
highlightField(error.field, error.message);
} else {
throw error; // not ours — let someone else handle it
}
}Re-throwing errors you don’t recognise is important: it stops your catch from hiding real bugs. A typo that causes a TypeError inside saveProfile would otherwise be shown to the user as a confusing “invalid email” message.
An error hierarchy for your app
Give all your app’s errors a shared base class. Then you can catch every one of them at once — or just one specific kind:
class AppError extends Error {
constructor(message, options) {
super(message, options);
this.name = this.constructor.name;
}
}
class ValidationError extends AppError {
constructor(field, message) {
super(message);
this.field = field;
}
}
class NotFoundError extends AppError {
constructor(resource, id) {
super(`${resource} ${id} was not found`);
this.resource = resource;
this.id = id;
}
}
class HttpError extends AppError {
constructor(response) {
super(`HTTP ${response.status} for ${response.url}`);
this.status = response.status;
}
}try {
await loadPage();
} catch (error) {
if (error instanceof AppError) {
showFriendlyMessage(error.message); // one of ours
} else {
reportBug(error); // a real bug — log it for developers
}
}this.constructor.name in the base class gives every subclass the right name automatically.
Wrapping errors with a cause
When you catch a low-level error and throw a clearer one, keep the original as its cause:
try {
await fetchCourse(id);
} catch (err) {
throw new Error(`Could not load course ${id}`, { cause: err });
}The new message explains what your program was trying to do; error.cause still holds the technical detail (a network error, a parse error) for debugging. The browser console shows both.
Using HttpError with fetch
Custom errors pair nicely with fetch, which doesn’t throw for HTTP error statuses on its own:
async function getJson(url) {
const res = await fetch(url);
if (res.status === 404) throw new NotFoundError('Resource', url);
if (!res.ok) throw new HttpError(res);
return res.json();
}Callers can now tell “doesn’t exist” from “the server broke” without inspecting status codes themselves.
Name things by meaning:
PaymentDeclinedErrortells a reader far more thanError('code 51').
How many error types?
Create a new type only when some caller needs to react differently to it. A handful — validation, not found, permission denied, network — covers most apps. If two errors are always handled the same way, one type with a clear message is enough.
A NotFoundError
Create NotFoundError that extends Error, sets its name, and stores the missing id. Then write findCourse(courses, id) that throws it when no course has that id.
class NotFoundError extends Error {
// your code here
}
function findCourse(courses, id) {
// your code here
}class NotFoundError extends Error {
constructor(id) {
super(`Nothing found with id ${id}`);
this.name = 'NotFoundError';
this.id = id;
}
}
function findCourse(courses, id) {
const course = courses.find((c) => c.id === id);
if (!course) throw new NotFoundError(id);
return course;
}Summary
- Extend
Errorto create error types for your own app. - Call
super(message), setname, and add any extra details callers may need. - Use
instanceofincatchto handle each kind differently, and re-throw the rest. - Wrap low-level errors with
{ cause }to keep the original details. - A shared base class lets you catch all of your app’s errors at once.