Thomas Step

This is where I share my thoughts and experiences that I encounter developing software.

Home


Blog


27 January 2022

How to Create a Custom Error Class in Javascript

This is going to be short and sweet.

class MyError extends Error {
  constructor(message) {
    super(message);

    this.name = 'MyError';
  }
}

module.exports = {
  MyError,
};

You can throw the error like so.

const { MyError } = require('./errors');

try {
  throw new MyError('This is my error that threw.');
} catch (err) {
  if (err instanceof MyError) {
    console.error('Instance of MyError found.');
  }

  console.error(err);
}
Categories: dev | javascript