Node.js: how to inspect errors?

MarcoS

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... :-(

chriskelly

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
  1. Node will break on the first line so type 'c' to continue.
  2. 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.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related