0

Attempting to utilize the approach outlined in this SO post.

I have the following typed exception:

    /**
     * @param message The error message
     * @param value The value that violates the constraint
     * @param field The name of the field
     * @param type The expected type for the field
     * @param code The application or module code for the error
     */
    export class IsError extends Error {
      constructor(
        public message:string,
        public value: any, 
        public field:string, 
        public type: string,
        public code?:string) {
          super(message);
          this.name = 'IsError';
      }
    }

This function throws it:

 export function isBooleanError(value: any, field:string, code?: string): void {
      if (!isBoolean(value)) {
        const message:string = `The field ${field} should be a boolean valued.  It is set to ${value}. `;
        throw new IsError(message, value, field, BOOLEAN_TYPE, code);
      }
    }

This works:

expect(()=>{isBooleanError({}, '')}).toThrow(Error);

But this does not:

expect(()=>{isBooleanError({}, '')}).toThrow(IsError);

Anyone know why the latter does not work? Jest logs:

expect(received).toThrow(expected)

Expected name: "IsError"
Received name: "Error"
skyboyer
  • 22,209
  • 7
  • 57
  • 64
Ole
  • 41,793
  • 59
  • 191
  • 359

1 Answers1

0

I had to add this to the constructor of the exception:

  super(message);
  Object.setPrototypeOf(this, IsError.prototype);      
Ole
  • 41,793
  • 59
  • 191
  • 359
  • And you need this to make `instanceof` work with subclasses of `Error`: see [#13965](https://github.com/Microsoft/TypeScript/issues/13965) – TmTron Mar 08 '19 at 07:26
  • Excellent point ... Is there some final recommendation of this. I read through the link, but it seems it was a bit up in the air. Would be nice to be able to use `instanceof`. Jest is able to check that the exception thrown is a `IsError`. Do you know what type of check it uses? – Ole Mar 08 '19 at 14:51
  • Asked follow up question here: https://stackoverflow.com/questions/55065742/implementing-instanceof-checks-for-custom-typescript-errors – Ole Mar 08 '19 at 14:58