如何解析请求回调中的错误参数?

How to parse error parameter in request callback?

我故意在某些条件下触发存储过程中的错误,我想在使用 Tedious 包的 Node.js API 中捕获。

来自 API 的代码片段:

        let request = new Request(sql, (err)=>{
            if (err) {
                sqlerr = err;
                console.log(typeof(err));
                console.log("**RQ-ERROR**", err);
            }
        });

上面"Request"对象的回调中有一个"err"参数。 "typeof()" returns "object";但是,当我将它转储到控制台时,它看起来像这样:

**RQ-ERROR** { RequestError: Duplicate entry for specified period
    at RequestError (C:\inetpub\wwwroot\PersonnelApps\kudosapi\node_modules\tedious\lib\errors.js:32:12)
    at Parser.tokenStreamParser.on.token (C:\inetpub\wwwroot\PersonnelApps\kudosapi\node_modules\tedious\lib\connection.js:723:34)
    at emitOne (events.js:96:13)
    at Parser.emit (events.js:188:7)
    at Parser.parser.on.token (C:\inetpub\wwwroot\PersonnelApps\kudosapi\node_modules\tedious\lib\token\token-stream-parser.js:27:14)
    at emitOne (events.js:96:13)
    at Parser.emit (events.js:188:7)
    at addChunk (C:\inetpub\wwwroot\PersonnelApps\kudosapi\node_modules\readable-stream\lib\_stream_readable.js:297:12)
    at readableAddChunk (C:\inetpub\wwwroot\PersonnelApps\kudosapi\node_modules\readable-stream\lib\_stream_readable.js:279:11)
    at Parser.Readable.push (C:\inetpub\wwwroot\PersonnelApps\kudosapi\node_modules\readable-stream\lib\_stream_readable.js:240:10)
  message: 'Duplicate entry for specified period',
  code: 'EREQUEST',
  number: 50000,
  state: 1,
  class: 16,
  serverName: 'PERSODG2LNN52\SQLEXPRESS',
  procName: 'CreateStatusReport',
  lineNumber: 44 }

这几乎看起来像一个 JavaScript 对象,但是,如您所见,"RequestError" 数据未被引用,也没有在文本“240:10)”之后的逗号就在前面"message" 成员。我不确定这是否是 TDS 中的错误,或者我是否只是遗漏了一些东西但我无法按原样访问任何成员。我必须将它转换为字符串并解析它,这很好但不是很优雅。

建议?

as you can see, the "RequestError" data isn't quoted nor is there a comma after the text "240:10)"

这些是控制台注销错误消息的产物。您可以使用以下内容亲自尝试一下:

$ node
> console.log(new Error('this is an error object!'));
Error: this is an error object!
    at repl:1:13
    at Script.runInThisContext (vm.js:119:20)
    at REPLServer.defaultEval (repl.js:332:29)
    at bound (domain.js:395:14)
    at REPLServer.runBound [as eval] (domain.js:408:12)
    at REPLServer.onLine (repl.js:639:10)
    at REPLServer.emit (events.js:194:15)
    at REPLServer.EventEmitter.emit (domain.js:441:20)
    at REPLServer.Interface._onLine (readline.js:290:10)
    at REPLServer.Interface._line (readline.js:638:8)

我不确定这个问题的预期结果是什么,但请尝试检查 err.message 属性 而不是使用 typeof 运算符。