3

I'm using an npm module that throws an empty function i.e. UnauthorizedException upon error. I want to be able to identify the function thrown so i can handle it accordingly

function UnauthorizedException() {

}

const f = () => {
  throw (new UnauthorizedException());
};

try {
  f();
} catch (err) {
  // How to identity a function name/property/etc so I can handle the error accordingly
  console.log(err);
  console.log(typeof (err));
}
aldred
  • 743
  • 3
  • 9
  • 19

1 Answers1

3

The UnauthorizedException function is used as constructor. You can check if an object was created from a constructor using the instanceof operator:

function UnauthorizedException() {}

const f = () => {
  throw (new UnauthorizedException());
};

try {
  f();
} catch (err) {
  console.log(err instanceof UnauthorizedException);
}
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
  • If this *is* the answer, though, surely this is a duplicate of [this](https://stackoverflow.com/questions/643782/how-to-check-whether-an-object-is-a-date) and a bunch of others? – T.J. Crowder May 30 '20 at 10:27
  • 2
    Sorry I wasn't aware it's a duplicate. Yes that is what I'm looking for i.e. instanceof. Thanks a lot – aldred May 30 '20 at 10:28