blakeembrey / javascript-stringify

Stringify is to `eval` as `JSON.stringify` is to `JSON.parse`
MIT License
139 stars 16 forks source link

stringifying an error is funny #30

Closed samuelt1 closed 4 years ago

samuelt1 commented 4 years ago

The following:

import { stringify } from 'javascript-stringify'
stringify(new Error('problem'))

stringifies like so: "new Error('problem')"

I was hoping it would stringify something more like: '{"message":"problem","stack":"Error: hi\nat <anonymous>:1:5 [<root>]","name":"Error"}'

I overcame this using custom replacers, which might be the only real solution seeing as how widely used this package is:

stringify(error , (obj) => {
  if (obj instanceof Error) {
    return stringify({
      message: obj.message,
      stack: obj.stack,
      name: obj.name,
    })
  } else {
    return stringify(obj)
  }
}, null, { references: true })
blakeembrey commented 4 years ago

Yes, using a custom replacer would be the best approach here. The goal is to replicate JavaScript as closely as possible, so the current behavior is preferable. Anywhere you'd want to deviate from outputting JavaScript you should override.