Javascript custom error basics

It's fairly straightforward to write your own custom error types in Javascript. The most basic syntax looks something like this:

class ArgumentError extends Error {
  constructor() {
    super(`The sensor is broken. Null temperature value detected.`);
  }
}

It's important to first understand the workings of the actual Error prototype, along with Javascript prototypal inheritance.

A Javascript class is a template for objects- it will always have a constructor method, which is automatically executed when a new instance of this class is created. If you don't include one, Javascript will include one for you.

The extends statement allows your object to access all of the methods and properties of the parent method.

In this context, it means that ArgumentError has access to all of the contents of Error. However, to actually access those contents you need to use the super function. The super function allows you to call the parent class constructor with the arguments provided, or call functions on the object's parent. In this context, the message about the sensor being broken is passed into super, which calls the parent Error constructor passing the message as an argument. The Error constructor takes a few optional parameters- providing the string will pass this as the message.

Effectively, this means that ArgumentError is simply an Error that is passed a specific message.

You can also pass a specific argument in a trivially more complex example:

export class OverheatingError extends Error {
  constructor(temperature) {
    super(`The temperature is ${temperature} ! Overheating !`);
    this.temperature = temperature;
  }
}

You can then perform checks against the property of the error, calling functions accordingly.

try {
    actions.check();
  } catch (error) {
    if(error instanceof ArgumentError) {
      actions.alertDeadSensor();
    } else if(error instanceof OverheatingError && error.temperature > 650) {
      actions.shutdown();
}