Name Your Own Errors

In the last exercise, your lending desk refused to lend a toy that was already out. It returned a string, though, as it did for a successful loan. The script that calls .lend() gets text either way, and it can’t tell a refusal from a loan slip without reading the words.

A thrown error is a better signal, and you already know how to catch one with an instanceof check that handles what it knows and rethrows the rest. In this lesson, you’ll give the library its own error classes, throw them from the desk, and write a catch block that tells them apart. Start with the question the course keeps asking: What is a failed loan?

Give a Failed Loan Its Own Class

The volunteers’ script needs to recognize a failed loan by its class instead of reading its message. “A loan error is an error” passes the “is a” test, so extends is the right tool here. The library may have other failures later, so start a small family with a base class for all of them:

Language: JavaScript Filename: errors.js
export class LibraryError extends Error {
  constructor(message, options) {
    super(message, options);
    this.name = this.constructor.name;
  }
}

export class LoanError extends LibraryError {
  constructor(message, toyId, options) {
    super(message, options);
    this.toyId = toyId;
  }
}

Watch out for the line this.name = this.constructor.name;. Without it, a subclass of Error still reports itself as Error: ..., because .name comes from Error.prototype and the class you wrote never sets it.

You set the name once, in LibraryError. In that line, this is the new LoanError object. It has no .constructor property of its own, and new doesn’t set one.

.constructor is an ordinary property, so the lookup walks up the chain to LoanError.prototype, whose .constructor is LoanError. So a LoanError gets "LoanError", and every later subclass gets its own name for free.

LoanError adds one field, .toyId, so the code that catches it can say which toy the loan was for without picking the ID out of the message.

Both constructors pass options on to super(). That’s how new LibraryError("Couldn't read loans.json", { cause: error }) keeps the original error as its .cause, as your wrapped SyntaxError did.

Save a short script to see what a LoanError reports:

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.