http-errors
http-errors copied to clipboard
Inconsistent error property enumerability
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.
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.
Ah, that's a good point. I can see either way, but it makes sense that it should be consistent.
Related past discussion: https://github.com/jshttp/http-errors/issues/20
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?
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
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