tc39 / proposal-is-error

ECMAScript Proposal, specs, and reference implementation for Error.isError
https://tc39.es/proposal-is-error/
MIT License
62 stars 2 forks source link

Beware of false negatives #5

Open brodo opened 4 months ago

brodo commented 4 months ago

First, I am delighted that this proposal reached stage 1 recently. I implemented support for printing aggregated errors to the console in Jest and faced difficulties determining whether an object was an error. You may want to add this to the list of use cases. In that process, I learned about Node's util.types.isNativeError(value), which you could add as prior work.

I also found out that several popular libraries and frameworks (e.g. Axios) create errors that are not returned by the Error constructor but merely are instanceof Error. You can find these libraries by searching for Error.call(this) on Sourcegraph.

That means that people will see the following behavior:

const myError = { __proto__: Error.prototype };
console.log(Error.isError(myError)); // false
console.log(myError instanceof Error); // true 

This could confuse people. It might be worth including an instanceof check in Error.isError().

I've also written an extensive article about how to test if an object is an error if people are interested.

ljharb commented 4 months ago

Thanks!

Those examples aren't native errors though, so the instanceof check would be wrong. Libraries like that need to do class extends Error if they want the native branding.