1

I'm trying to convert object to string using JSON.stringify and I get empty object

console.log('typeof',typeof e,' e value is',e, 'JSON stringify is',JSON.stringify(e))

the error message when I try to print

typeof object e value is Error: Error: A network error (such as timeout, interrupted connection or unreachable host) has occurred. JSON stringify is {}

enter image description here

Manspof
  • 598
  • 26
  • 81
  • 173
  • 1
    @ManuallyOverridden `console.log` is variadic — you can pass multiple objects, which are separated by a `,`. – Mark Jul 01 '18 at 06:38
  • It looks like `e` is an error object. In node, stringifying an error results in `{}`. Not sure how you are running your code. – Mark Jul 01 '18 at 06:40
  • @ManuallyOverridden even I do let a = JSON.stringify(e) and I print a I get empty object.. – Manspof Jul 01 '18 at 06:40
  • @Mark_M how can I print error object? I want use it to string and show in client side – Manspof Jul 01 '18 at 06:45
  • See this answer https://stackoverflow.com/questions/18391212/is-it-not-possible-to-stringify-an-error-using-json-stringify – wizebin Jul 01 '18 at 06:47

1 Answers1

3

Your object e is an error object. When you try to stringify that you get {} in chrome and node. Safari shows a little more info.

let e = new Error("hello")
console.log(typeof e)
console.log(JSON.stringify(e))

You can test for errors with:

let e = new Error("Some error happened")
if (e instanceof Error) {
  console.log("Error:", e.message)
 }
Mark
  • 90,562
  • 7
  • 108
  • 148