0

I saw a very special (and weird) error handling code, which goes like this:

function SomeError(name, message) {
    this.name = name;
    this.message = message;
    this.stack = (new Error()).stack;
}
SomeError.prototype = Object.create(Error.prototype);

On promise catch:

promise.catch(e => {
    throw new SomeError('someName', e.message);
});

My question:
Is there any reasonable cause to make it this way?
I thought of handling this like:

promise.catch(e => {
    e.name = 'my error name';
    throw new Error(e);
});
Yinon
  • 945
  • 1
  • 8
  • 21

1 Answers1

0

Because it allows you to fine grain the catching:

 // Somewhere up the promise chain:
 .catch(error => {
    if(error instanceof SomeError) {
      // Handle this specific case
    } else { /* handle other cases */}
  });

The code that defines SomeError could be rewritten as the following class which makes clear what it is doing:

 class SomeError extends Error {}

It basically just creates a subclass that does nothing.

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
  • See also [this question](https://stackoverflow.com/q/1382107/1048572) for various pre-ES6 ways to extend `Error` – Bergi Jul 30 '18 at 16:19