Thomas Step

← Blog

I recently launched a Slack app to help with channel bloat! Simply installing it would help me out a bunch. I have 2/10 installations required to submit my app to the Slack Marketplace. Thanks for helping me reach that goal.

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