CodeBlanks Logo Icon CodeBlanks

Custom errors

Learn to write your own Error-derived class.

Custom errors

Sometimes you want to tell the type of an error apart. A custom error is a subclass derived from the Error class. It is defined with class ValidationError extends Error.

In the subclass you write a constructor and call the parent's constructor with super(message). You also set the this.name property to the class name, so err.name returns "ValidationError". For example, you define separate classes to tell a validation error from a network error. You can also check the type with instanceof: err instanceof ValidationError. This keeps error management organized in complex apps.

constructor and super

In a custom error class, the constructor method must call the parent's constructor with super(message). This ensures message and stack are set correctly.

For example, class ValidationError extends Error { constructor(message) { super(message); this.name = "ValidationError"; } }. If super(message) is not called, this cannot be used; this throws a ReferenceError. If this.name is not set, the default "Error" stays, which makes telling types apart harder. instanceof still works, but you may also want to see the type as a string with name. So doing both is best.

Practice Write a ValidationError class and catch it

Define a ValidationError class that extends Error. In constructor(message) set super(message) and this.name = "ValidationError". In try throw new ValidationError("invalid"), in catch (e) print console.log(e.name).

Starter code

index.js
// Define a ValidationError class (extends Error)
// In constructor set super and this.name
// Throw in try, print name in catch
// write here

Sample solution

index.js
class ValidationError extends Error {
  constructor(message) {
    super(message);
    this.name = "ValidationError";
  }
}
try {
  throw new ValidationError("invalid");
} catch (e) {
  console.log(e.name);
}

Expected output

ValidationError

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match each piece to its role

Term Meaning
extends Error Derives from Error
super(message) Calls the parent class
this.name Sets the error type
class Defines a new class

2 Why is this.name set in a custom error class?

index.js
this.name = "ValidationError"
  • For memory
  • To tell the error type apart Correct answer
  • It is unnecessary
  • For performance

Explanation: With name you tell the type of the error apart.

3 Derive with extends

Question
class ValidationError ____ Error {}
Answer
class ValidationError extends Error {}

Explanation: extends Error derives from Error.

All lessons in Intermediate