Reputation: 1905
I am trying to log my errors and send notification to a channel. When I use console.log() I get a description of the error message but when I use JSON.strigify it returns an empty object. How can I fix this issue please.
When I run this code:
console.log(err);
console.log("stringify", JSON.stringify(err));
I get this response:
ReferenceError: School is not defined
at /Users/macbookpro/Documents...
at Layer.handle [as handle_request] (/Users/macbookpro/Documents...
at next (/Users/macbookpro/Documents...
at adminAccess (/Users/macbookpro/Documents...
at processTicksAndRejections (node:internal/process/task_queues:96:5)
strinfify {}
I need the error message, and for me to send it successfully using axios, I need to JSON.stringify() the error message.
Upvotes: 2
Views: 1966
Reputation: 9497
The simpliest option is to add additional parameter to JSON.stringify
JSON.stringify(error, Object.getOwnPropertyNames(error))
Error object properties are not enumerable, thus without specifying them explicitly you're not able to get them. But if you fetch property names as a second parameter of JSON.stringify
you're able to retrieve them.
Upvotes: 0
Reputation: 64705
Most properties on an error object are non-enumerable, so you need to do something like this:
let error = new Error('nested error message');
console.log(JSON.stringify(error))
console.log(JSON.stringify(Object.assign({},
error,
{ // Explicitly pull Error's non-enumerable properties
name: error.name,
message: error.message,
stack: error.stack
}
)))
Upvotes: 5