Custom errors

Topic 2 of 3 in Error handling5 min readBeginnerFree course

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:

JavaScript
class ValidationError extends Error {
  constructor(field, message) {
    super(message);
    this.name = 'ValidationError';
    this.field = field;
  }
}

Error is the parent of the built-in TypeError, RangeError and SyntaxError, and of your own ValidationError and NotFoundError. In a catch block, check instanceof ValidationError to highlight the field, instanceof NotFoundError to show a not-found page, and otherwise re-throw.

Anatomy of a custom error

JavaScript
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
  }
}
  1. super(message) runs the built-in Error constructor, which sets message and captures the stack trace.
  2. name is what the console prints before the message: ValidationError: Please enter…. Without it, it would just say Error.
  3. 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

JavaScript
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:

JavaScript
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;
  }
}
JavaScript
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:

JavaScript
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:

JavaScript
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: PaymentDeclinedError tells a reader far more than Error('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.

Exercise

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.

JavaScript
class NotFoundError extends Error {
  // your code here
}

function findCourse(courses, id) {
  // your code here
}

Summary

  • Extend Error to create error types for your own app.
  • Call super(message), set name, and add any extra details callers may need.
  • Use instanceof in catch to 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.