convert object to string using JSON.stringify show empty object


convert object to string using JSON.stringify show empty object



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





@ManuallyOverridden console.log is variadic — you can pass multiple objects, which are separated by a ,.
– Mark Meyer
Jul 1 at 6:38


console.log


,





It looks like e is an error object. In node, stringifying an error results in {}. Not sure how you are running your code.
– Mark Meyer
Jul 1 at 6:40


e


{}





@ManuallyOverridden even I do let a = JSON.stringify(e) and I print a I get empty object..
– Adir Zoari
Jul 1 at 6:40





@Mark_M how can I print error object? I want use it to string and show in client side
– Adir Zoari
Jul 1 at 6:45





See this answer stackoverflow.com/questions/18391212/…
– wizebin
Jul 1 at 6:47




1 Answer
1



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.


e


{}




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)
}






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

List of Kim Possible characters

Audio Livestreaming with Python & Flask

NSwag: Generate C# Client from multiple Versions of an API