Reputation: 2961
This looks similar to console.log inconsistent with JSON.stringify, but: I'd like to know what exactly happens behind the screen, because I can't understand what exactly happens here, and why JSON.stringify() does not show the error text. Here's my code (saved in firstio.js)
var fs = require('fs')
try {
var file = fs.readFileSync(process.argv[2])
}
catch(error) {
console.log(error.toString());
console.log(JSON.stringify(error, null, 2));
process.exit()
}
console.log(file.toString().split("\n").length - 1)
when run as follows: node firstio.js
the output is as follows:
TypeError: path must be a string
{}
If JSON.stringify is converting the error object where is the error text that toString() apparently can find?
When it is run as follows: node firstio.js nonexistingfile
the output is:
Error: ENOENT, no such file or directory 'nonexistingfile'
{
"errno": -2,
"code": "ENOENT",
"path": "nonexistingfile",
"syscall": "open"
}
Upvotes: 0
Views: 707
Reputation: 3098
Method JSON.stringify()
process objects based on their enumarable properties.
But window.Error
object does not have any enumerable properties thus JSON.stringify(error)
returns only empty object.
You can write an error directly into console:
console.log(new Error('Something happened'));
Which will output Error: Something happened
.
Or you can write your own method to stringify error; see Is it not possible to stringify an Error using JSON.stringify?
Upvotes: 1