Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Error should have a toJSON implementation? #29090

Closed
ORESoftware opened this issue Aug 12, 2019 · 3 comments
Closed

Error should have a toJSON implementation? #29090

ORESoftware opened this issue Aug 12, 2019 · 3 comments
Labels
feature request Issues that request new features to be added to Node.js.

Comments

@ORESoftware
Copy link
Contributor

ORESoftware commented Aug 12, 2019

Just playing with some code and discovered that JSON.stringify called against Error instances are empty objects which seems weird since message and stack are string properties? And since errors are usually of interest.

console.log(JSON.stringify(new Error('foo')));  //  {}


class Foo extends Error {
  
  constructor() {
    super(...arguments);
  }
  
  toJSON() {
    return {
      message: this.message,
      stack: this.stack
    }
  }
  
}

console.log(JSON.stringify(new Foo('foo')));   // now we have some output

maybe the Error class should come with a toJSON implementation?

@Trott Trott added the feature request Issues that request new features to be added to Node.js. label Aug 12, 2019
@benjamingr
Copy link
Member

Errors are part of JavaScript - or do you mean Node core's internal errors?

@AyushG3112
Copy link
Contributor

AyushG3112 commented Aug 12, 2019

Regarding the reason you don't get stack and message in JSON.stringify

Object.getOwnPropertyDescriptors(new Error("test"))

returns

{
  "stack": {
    "value": "Error: test\n    at <anonymous>:1:49",
    "writable": true,
    "enumerable": false,
    "configurable": true
  },
  "message": {
    "value": "test",
    "writable": true,
    "enumerable": false,
    "configurable": true
  }
}

stack and message are non-emunerable, hence not included in JSON.stringify result.

@ORESoftware
Copy link
Contributor Author

ORESoftware commented Aug 12, 2019

Yeah I figured the fact that they were non-enumerable properties was it. Tell the V8 people I guess, seems weird that you wouldnt want to see error stack/messages in serialized data, although good for security in some cases.

You can close this one - people can extend Error if they really want to serialize them or what not.

@devsnek devsnek closed this as completed Aug 12, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
feature request Issues that request new features to be added to Node.js.
Projects
None yet
Development

No branches or pull requests

5 participants