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)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay