jmazin
jmazin

Reputation: 1377

What's a simple way to log a programming error in node?

NOTE: I edited this question to more accurately show the problem, rather than delete and rewrite it. Hope that's OK.

For the following code:

var Q = require('q');

function first (){
  var d = Q.defer();

  setTimeout(function(){
    d.resolve([]);
  }, 1000);

  return d.promise;
}

function second(v){
  sdf;
  console.log("hi")
}

first()
.then(second);

How can I determine that there is a ReferenceError in there? Is the only option to add a second function argument in the then call?

Even though it's not recommended, I tried using process.on('uncaughtException') but to no avail.

Thanks!

Upvotes: 0

Views: 108

Answers (3)

Chris Tavares
Chris Tavares

Reputation: 30411

Rewrite your final call like this:

function errorHandler(err) {
  console.log('You had an error, ' + err);
}

first
  .then(second, errorHandler);

The promise captures any exceptions that throw within it, you need to explicitly handle it.

A variation that's q specific would be:

first
  .then(second)
  .fail(errorHandler);

You may consider this easier to read.

Upvotes: 1

deepseadiving
deepseadiving

Reputation: 763

It really depends what your stack trace looks like. If you're using express or restify, for example, you may actually need to listen for the uncaughtException event on your server object. The error is normally not lost; put something like this into a sample JS file:

null.f();

and you'll see a TypeError thrown, as you are expecting.

If you're not sure of the stack, log it:

console.log(new Error("this is my stack").stack);

Upvotes: 0

photon
photon

Reputation: 616

I think it may be appropriate to catch the error before the declaration of the contract object. So something like this:

map(locations, function(loc) {
    if(!loc.ClientId) {
        console.log("Error: loc.ClientId is undefined");
    } else {
        var contract = {
            "clientName": clients[loc.ClientId][0]
        }
        ...
    }
})

Here the error is logged to console when loc.ClientId is undefined.

Upvotes: 0

Related Questions