Reputation: 17711
I am quite puzzled by Node.js Error
object, when logged to console...
As an example, I have this code:
request(
options,
function (err, response, contents) {
if (err) {
console.error('error in request:', err);
}
success(contents);
},
);
Sometimes it errors out for an ECONNRESET
error... So far so good.
The console.error()
(or console.log()
) format is this:
[Error: socket hang up] code: 'ECONNRESET'
I cannot understand the format printed: why "Error: socket hang up" is among square brackets? Is it an object? One for all: how can I inspect error object so I can see all individual properties?
UPDATE: Following @chriskelly answer, after running node in debug mode, I get:
debug> repl
Press Ctrl + C to leave debug repl
> typeof err
'object'
> Object.keys(err)
[]
> console.dir(err)
< [Error: socket hang up] code: 'ECONNRESET'
I keep not understanding err
object: no keys, but is has content... :-(
Upvotes: 4
Views: 3611
Reputation: 7736
The error type returned by request is an Error object: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error
One of its properties is an array called properties and the second entry contains the text you see in square brackets. Javascript makes it possible to specify varying degrees of visbility and some custom objects such as Error have these properties set: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties
Try running node with the debug
switch and use debugger
keyword to create breakpoint. i.e. Modify your code as follows:
if (err) {
console.error(err)
debugger;
}
Then run node as follows:
node debug server.js
When it stops at the line above, type repl
(stands for read, eval, print, loop) to inspect variables
e.g. type
Object.keys(err)
to inspect properties of err (Assuming it's an object).
Fyi, for a graphical alternative you could try node-inspector which you can install with:
npm install -g node-inspector
then run with
node-debug server.js
Your code will open in Chrome and give you the same tools available during front-end debugging.
HTH.
Upvotes: 2
Reputation: 1841
Also you can use:
console.dir(err);
https://developer.mozilla.org/en-US/docs/Web/API/Console/dir
UPDATE:
This is a doc about Error object:
https://nodejs.org/api/errors.html
In square brackets Error shows Type and Message. Type is error class, and message - the parameter passed to error constructor.
var e = new TypeError("Bla Bla Bla");
console.log(e);
Gives: [TypeError: Bla Bla Bla]
Upvotes: 4