http-errors icon indicating copy to clipboard operation
http-errors copied to clipboard

Inconsistent error property enumerability

Open jaydenseric opened this issue 7 years ago • 6 comments

You would expect these usages to log identically:

import createError from 'http-errors'

console.log(
  JSON.stringify(createError('Message 1.')),
  JSON.stringify(createError(new Error('Message 2.')))
)

They actually output this:

{"message":"Message 1."} {"expose":false,"statusCode":500,"status":500}

For context, I am attempting to do snapshot testing of errors that have been created various ways and am having many surprises.

jaydenseric avatar Jun 06 '18 10:06 jaydenseric

If it helps guide what the right behavior should be, the JSON representation of a normal Error instance is {}:

console.log(JSON.stringify(new Error('Message.')))

Consistency with native errors might make sense, although for the purposes of snapshot testing I wish all of the properties were enumerable.

jaydenseric avatar Jun 06 '18 11:06 jaydenseric

Ah, that's a good point. I can see either way, but it makes sense that it should be consistent.

dougwilson avatar Jun 06 '18 14:06 dougwilson

Related past discussion: https://github.com/jshttp/http-errors/issues/20

jaydenseric avatar Jun 06 '18 15:06 jaydenseric

So the issue is that the properties you are getting in the output are just the ones we are touching inside the factory and JSON.stringify ignores properties on the prototype.

All the properties we add are enumerable so it seems like the issue here is that Json.stringify doesn't print out properties on the prototype, hm... I'm not sure what a good solution would be.

Does anyone have some thoughts on this?

dougwilson avatar Sep 07 '18 12:09 dougwilson

Actually for some reason message is now enumerable when for a classic error it is not. And statusCode is not enumerable.

This is really weird, and it seems to have been done because someone is trying to JSON.stringify it. But it should not be the problem of http-errors

jeanbaptiste-brasselet avatar Jan 03 '19 11:01 jeanbaptiste-brasselet

Hi everyone, as an update, the 3.0 release will address this by setting all properties as non-enumerable, which matches how ECMA-262 works with errors: https://tc39.es/ecma262/#sec-error-message

dougwilson avatar Nov 15 '21 01:11 dougwilson