Is it safe to use `instanceOf` when the Error is used and defined in different libraries?

Viewed 41

Given say three libraries, where library A defines a new error:

class CustomError extends Error { }

and library B and C imports and throws this error, is it safe for my project to use instanceof to check for this error? E.g.

const { CustomError } = require('@so/errors');
const doSomething = require('@so/doSomething');   // imports `CustomError` from `@so/errors`
const doSomething2 = require('@so/doSomething2'); // imports `CustomError` from `@so/errors`

try {
  doSomething();  // can throw `CustomError`
  doSomething2(); // can throw `CustomError`
} catch (err) {
  // is this check reliable?
  if(err instanceof CustomError) {
    console.log('caught!');
  }

  throw err;
}

Or does it depend on npm to symlink both @so/doSomething and @so/doSomething2 to the same @so/errors package I am using? If so, does that mean @so/errors has to be at the same version that @so/doSomething and @so/doSomething2 depends on?

0 Answers
Related