0

I have a jQuery AJAX function that sends some JSON data off to be stored in my postgresql database, I am using Node, Express and node-pg.

$.ajax({
  type: 'POST',
  data: newUser,
  url: '/adduser',
  dataType: 'JSON'
})
.done(function( response ) {

  // Do something

})
.fail(function(errormsg) {

// Alert the sql error
alert(errormsg.responseText);

});

And in dealing with the insert in NodeJS on the client side I have

db.query('INSERT INTO userlist (' + keys + ')  values ( ' + preppedString + ')', values, function(err, result) {

  if (err){
    var errorMessage = ("" + err);
    res.send(errorMessage);
  } else {
    res.send(result);
 }
});

Now, the problem is with the error message reporting. If I send the error message to the client side using

    var errorMessage = ("" + err);
    res.send(errorMessage);

It works perfectly - you get an alert saying stuff like "error: invalid input syntax for integer: "ds""

However, if i remove the string concatenation and just do

    var errorMessage = err;
    res.send(errorMessage);

It doesn't work at all - doesn't fire the .fail AJAX option (I think) and doesn't alert (definitely).

I'm not really too concerned with it - the first option with concatenation works fine, just wondering why it is behaving in that manner

Clodoaldo Neto
  • 118,695
  • 26
  • 233
  • 260
Winters
  • 980
  • 3
  • 11
  • 16
  • 2
    Maybe `err` is not string? try using type conversion, something like `errorMessage = err.toString()` – Michał Mar 09 '14 at 10:20
  • Definitely seems to be the case. The string that is output is the first property of the error object. Is there a better way I should be doing this? – Winters Mar 09 '14 at 10:26
  • 2
    How about `err.message` or `err.name`? Take a look here for Error Object properties: http://stackoverflow.com/questions/10624873/what-properties-does-nodejs-expresss-error-object-exposes – Michał Mar 09 '14 at 10:30
  • winner winner - err.message did the trick. If you want to formulate that into an answer I'll accept. thanks for your help – Winters Mar 09 '14 at 10:41

1 Answers1

1

You are looking for Error Object's message property:

var errorMessage = err.message;
res.send(errorMessage);
Michał
  • 2,456
  • 4
  • 26
  • 33