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

Time:08-05

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:

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

CodePudding user response:

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.

  • Related