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

标签 javascript json node.js postgresql

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

Node 版本:v0.10.38 pg-promise 版本:1.1.4

由于无关紧要的微不足道的错误配置问题,我遇到了连接错误。但我希望我的脚本通过对问题的丰富解释来提醒我。

如果我将错误对象传递给错误处理程序回调并通过 console.log() 将其“按原样”发送到控制台,那么我将看到文本“没有主机“127.0.0.1”的 pg_hba.conf 条目”以您可以在标记为“输出 1”中看到的方式。

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

此外,如果我在该对象上记录 JSON.stringifgy() 的结果,该信息就会消失。

这是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() 方法(或强制字符串强制转换)来获取该字符串。

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

我发现我可以通过重载对象原型(prototype)中的 .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());

如果你使用字符串连接,它应该有同样的效果:

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

后一种方式好像是怎样pg-promise README example code处理错误。

我已经用 pg-promise 测试了这两个,它们都可以工作,但是它们会打印“错误:”作为消息的一部分,所以你真的不需要包含“错误! ' 就像我一样。

关于javascript - JSON 错误对象中奇怪的未命名属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30182426/

相关文章:

javascript - 测试异步 SQS sendMessage

javascript - 基于页面高度的css三 Angular 形

javascript - 比较 JSON 返回的参数值

Javascript 箭头函数没有按预期工作?

返回未定义的 JavaScript 对象

javascript - 前端的 Meteor,后端的 Express (NodeJS)

node.js - 如何在实时服务器或网站中执行 Node js 代码

javascript - d3.json回调函数

Android JSON 发布到 WCF 服务

javascript - 对 json 数据进行排序