io-ts icon indicating copy to clipboard operation
io-ts copied to clipboard

Allow Error to be decoded with UnknownRecord

Open louix opened this issue 4 years ago • 1 comments

Some libraries (e.g. AWS SDK, Axios) will throw Errors, but won't export the actual Error itself which prevents an e instanceof XError check.

It's useful to be able to write a codec for these Errors, but no longer works after 2.0.5 (previous implementation).

Related to issue #485.

louix avatar Oct 12 '21 13:10 louix

I'm running into this issue now, it was very surprising to find that UnknownRecord doesn't consider instances of Error to be compatible.

Concretely, the following returns false, where I believe it should return true:

t.type({}).is(new Error()); // false

Is there a compelling reason for why Error should not be included here?

bradleyayers avatar Mar 17 '22 04:03 bradleyayers

I also ran into this issue, we switched to a fork with this PR applied which is working well so far.

The fix in this PR still allows some surprising behavior on weird objects though, since Object.prototype.toString can be customized like this:

const obj = { [Symbol.toStringTag]: 'something' };
Object.prototype.toString.call(obj); // '[object something]'

It looks like the original intention of the change in 2.0.5 was just to exclude arrays from UnknownRecord. The most reliable way to do that is probably to exclude arrays explicitly, rather than trying to build a list of non-array types that are allowed. For example, with Array.isArray:

u !== null && typeof u === 'object' && !Array.isArray(u)

GriffinSchneider avatar Oct 04 '22 19:10 GriffinSchneider

Fix: https://github.com/gcanti/io-ts/releases/tag/2.2.19

gcanti avatar Oct 06 '22 12:10 gcanti