DEV Community

Thomas Step
Thomas Step

Posted on • Originally published at thomasstep.com

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,
};
Enter fullscreen mode Exit fullscreen mode

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);
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)