Standardize `error.code`?

When handling errors, a common need is to detect what type of error you have. Currently, the only ways per spec are quite suboptimal:

  1. String matching on error.message , which is extremely fragile
  2. Creating (often pointless) subclasses for every possible error, for the sole purpose of detection. Deno seems to follow that approach: https://docs.deno.com/api/deno/\~/Deno.errors . That’s …a lot of subclasses.

NodeJS supports an error.code property for specifying an error id (e.g. "ENOENT”) that is guaranteed to be more stable. It seems to be added ad hoc on Error instances ("code” in Error.prototype returns false ) and authors need to create their own abstractions if they want to use a similar mechanism, as there is no way to create an Error with a code through the Error constructor: passing code as an option is simply ignored. Bun does this too.

I wonder if it would make sense to standardize a code option that could be passed to the Error constructor for specifying such stable codes, so it could be depended on, and available to authors without custom abstractions.

This is on the agenda for the upcoming March meeting:

1 Like

The proposal just allows user-created errors to define a code, rather than requiring specification-thrown errors to have a code.

Requiring specification-thrown errors to have a code would significantly constrain engines - many algorithms throw errors at multiple places with no user-observable code between them, which allows implementation strategies which do not distinguish between those types of errors; requiring a code would prevent them from doing this.

@senocular Wow, that’s some timing! Thank you for the pointer!

@bakkot What I was proposing was exactly what GitHub - jasnell/proposal-error-code-property is proposing!

I do think it would be a good idea generally for platform errors to have error.code once it’s available, but that should be a design principle, not a spec requirement (for a variety of reasons, one of which you mention).

Okay, I’ll go ahead and archive this then, since this is already a thing. Awesome!