Expressjs不会从msnodesqlv8 err对象返回所有属性

时间:2019-02-11 15:27:13

标签: node.js express

在下面的代码中,我试图连接到SQL Server上不存在的数据库,从而导致错误(作为说明)。

const sql = require("msnodesqlv8");
const express = require("express");
const app = express();

// Start server and listen on http://localhost:8081/
const server = app.listen(8081, function () {
    console.log("Server listening on port: %s", server.address().port)
});

const connectionString = "Server=.;Database=DatabaseThatDoesNotExist;Trusted_Connection=Yes;Driver={SQL Server Native Client 11.0}";
const sql = "SELECT * FROM dbo.Table1";

app.get('/', function (req, res)
{
    sql.query(connectionString, sql, (err, recordset) => {
        if(err)
        {
            console.log(err);
            res.status(500).send(err);
            return;
        }

        // else
        res.json(recordset);
    });
})

console.log(err);的结果列出了具有四个属性(代码,消息,sqlstate和堆栈)的错误对象:

Array(2) [Error: [Microsoft][SQL Server Native Client 11.0][…, Error: [Microsoft][SQL Server Native Client 11.0][…]
codefile.js:33
length:2
__proto__:Array(0) [, …]
0:Error: [Microsoft][SQL Server Native Client 11.0][SQL Server]Login failed for user 'DOMAIN\USER'.
code:18456
message:"[Microsoft][SQL Server Native Client 11.0][SQL Server]Login failed for user 'DOMAIN\USER'."
sqlstate:"28000"
stack:"Error: [Microsoft][SQL Server Native Client 11.0][SQL Server]Login failed for user 'DOMAIN\USER'."
__proto__:Object {constructor: , name: "Error", message: "", …}
1:Error: [Microsoft][SQL Server Native Client 11.0][SQL Server]Cannot open database "MyDatabase" requested by the login. The login failed.
code:4060
message:"[Microsoft][SQL Server Native Client 11.0][SQL Server]Cannot open database "MyDatabase" requested by the login. The login failed."
sqlstate:"42000"
stack:"Error: [Microsoft][SQL Server Native Client 11.0][SQL Server]Cannot open database "MyDatabase" requested by the login. The login failed."
__proto__:Object {constructor: , name: "Error", message: "", …}

但是,res.status(500).send(err);的结果(在客户端中可见)仅包含两个属性(sqlstate和代码):

[
    {
        "sqlstate": "28000",
        "code": 18456
    },
    {
        "sqlstate": "42000",
        "code": 4060
    }
]

我如何获得快递以同时返回消息和堆栈属性?

1 个答案:

答案 0 :(得分:0)

问题是Error没有可枚举的字段,因此messagestack没有序列化为JSON。

有关this question序列化错误对象的方法,请参见。

针对您的情况的快速解决方案:res.status(500).send({message: err.message, stack: err.stack});

但这当然是不可扩展的。更好的方法是配置json replacer for express

app.set('json replacer', replaceErrors);

并使用@ jonathan-lonowski所链接问题的出色答案中的replacer实现:

function replaceErrors(key, value) {
  if (value instanceof Error) {
    var error = {};

    Object.getOwnPropertyNames(value).forEach(function (key) {
        error[key] = value[key];
    });

    return error;
  }
  return value;
}