JSON错误对象中的奇怪未命名的属性

我在node.js控制台脚本中使用pg-promise 。

节点版本:v0.10.38 pg-promise版本:1.1.4

由于不重要的错误configuration问题,我得到了连接错误。 但是我希望我的脚本能够对这个问题提供丰富的解释。

如果我将传递给error handling程序callback的错误对象以“原样”的forms通过console.log()发送给控制台,那么我可以看到文本“no pg_hba.conf”作为主机“127.0.0.1”条目你可以看到标签为“输出1”。

但是,如果这似乎不是一个有效的JSON对象,我不知道如何访问该消息的属性。

另外,如果我将JSON.stringifgy()的结果logging在该对象上,则该信息就会消失。

这是pg-promise实现的错误吗? 或者它是某种JSON隐藏的属性,可以以任何方式访问?

以下是对这个问题的再现:

源代码:

var pgpLib = require('pg-promise'); var pgp = pgpLib({}); var db = pgp({ host: "localhost", database: "__db_name__", user: "__db_user__", password: "__db_password__", }); db.query("select 'foo'").then( function(){ console.log ("Works!!"); }, function(err){ console.log("ERROR!!", err); // (Output 1) // console.log("ERROR!!", JSON.stringify(err)); // (Output 2) } ); 

输出1:

 ERROR!! { [error: no pg_hba.conf entry for host "127.0.0.1", user "reports", database "ruminant", SSL off] name: 'error', length: 143, severity: 'FATAL', code: '28000', detail: undefined, hint: undefined, position: undefined, internalPosition: undefined, internalQuery: undefined, where: undefined, schema: undefined, table: undefined, column: undefined, dataType: undefined, constraint: undefined, file: 'auth.c', line: '493', routine: 'ClientAuthentication' } 

输出2:

 ERROR!! {"name":"error","length":143,"severity":"FATAL","code":"28000","file":"auth.c","line":"493","routine":"ClientAuthentication"} 

编辑

正如Trott所说(谢谢),我可以通过使用.toString()方法(或强制string强制)来获取该string。

但是,无论如何,下面的输出对我来说似乎不是有效的JSON。

我想通过在对象原型中重载.toString()方法可以达到同样的效果,但是我不能:

 var foo = function(){}; Object.defineProperty(foo.prototype, "toString", { enumerable: false, value: function() { return "Some hidden data"; } }); var bar = new foo(); console.log("1:", bar, bar.toString()); bar.otherStuff = "foobar"; console.log("2:", bar, bar.toString()); 

输出:

 1: {} Some hidden data 2: { otherStuff: 'foobar' } Some hidden data 

为了只从Error对象中获取错误消息而不使用其他所有东西,请使用.toString()

 console.log('ERROR! ', err.toString()); 

如果你使用string连接,它应该有相同的效果:

 console.log('ERROR! ' + err); 

后一种方式似乎是pg-promise README示例代码处理错误的方式。

我已经testing了这两个pg-promise ,他们工作,但他们打印“错误:”作为他们的消息的一部分,所以你不需要包括'错误! “就像我做的一样。