Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unable to check if thrown error is an instance of a custom error class

I have created a custom error class which extends the built-in Error class and adds a new value to it. The error itself works as expected.

I want to handle this error explicitly when I catch it.

This is my custom error class:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

export default class CustomHttpError extends Error {
  constructor(readonly httpCode: number, readonly message: string) {
    super(message);

    this.name = 'CustomHttpError';
  }
}

This is how I am trying to test it:

const CustomHttpError = require('./lib/src/errors/CustomHttpError');

try {
  throw new CustomHttpError(420, 'Enhance Your Calm');
} catch (e) {
  if (e instanceof CustomHttpError) {
    console.log(CustomHttpError.httpCode);
  }
}

I receive this error:

  if (e instanceof CustomHttpError) {
        ^

TypeError: Right-hand side of 'instanceof' is not callable

>Solution :

Assuming that you’re using TypeScript in the main module, instead of require, you probably want to do

import CustomHttpError from './lib/src/errors/CustomHttpError';

Although you could do

const CustomHttpError = require('./lib/src/errors/CustomHttpError').default;

This is happening based on your tsconfig.json‘s esModuleInterop setting. You can read more about it here.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading