Skip to content

Seems t.throws is not matching errors properly by Prototype for ES6 classes that extend Error #15055

@maxclaus

Description

@maxclaus

Using ava which has a copy of node assert module I realized few tests trying to match a custom error with t.throws were failing.

  assert.throws(
    () => deleteItem(initialState, operation),
    NotFoundObject
  );

Although this custom error is extending from Error class:

import ExtendableError from 'es6-error';

class CustomError extends ExtendableError {
  constructor(message, httpStatusCode, data) {
    super(message);
    this.httpStatusCode = httpStatusCode;
    this.data = data;
  }

  toString() {
    const message = super.toString();
    return (
      this.data
      ? `${message}. Error data: ${JSON.stringify(this.data, null, 2)}`
      : message
    );
  }
}

export class NotFoundObject extends CustomError {
  constructor(objectId, objectType) {
    super(`${objectType || 'Object'} with id ${objectId} does not exist`, 400);
  }
}

Digging into the code I found the assert is returning false if the expected error is a prototype of Error. Which doesn't make sense. It should return true since it is a prototype of Error:

  if (Error.isPrototypeOf(expected)) {
    return false;
  }

https://github.com/nodejs/node/blob/master/lib/assert.js#L584

So, am I reading that code wrong and it should really return false?


Reference initial issue found on ava assert module: sindresorhus/core-assert#2

Metadata

Metadata

Assignees

No one assigned

    Labels

    assertIssues and PRs related to the assert subsystem.questionIssues that look for answers.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions