我目前正在使用'请求承诺'来自node-js的API调用的库,并努力从' catch'中获取正确的调用栈。功能。在玩了一下之后,我注意到了一个我无法解释的有趣行为。说我有代码:
.catch(err => {
console.log(err.stack);
console.log('!!!');
console.log(new Error().stack);
});
在控制台中,我实际上看到两个完全不同的堆栈跟踪,用于“错误”。和'新错误()' :
StatusCodeError: 404 - [object Object]
at new StatusCodeError (C:\MyProject\request-promise\lib\errors.js:26:15)
at Request.RP$callback [as _callback] (C:\MyProject\request-promise\lib\rp.js:68:32)
at Request.self.callback (C:\MyProject\request-promise\node_modules\request\request.js:187:22)
at Request.emit (events.js:110:17)
at Request.<anonymous> (C:\MyProject\request-promise\node_modules\request\request.js:1048:10)
at Request.emit (events.js:107:17)
at IncomingMessage.<anonymous> (C:\MyProject\request-promise\node_modules\request\request.js:969:12)
at IncomingMessage.emit (events.js:129:20)
at _stream_readable.js:908:16
at process._tickCallback (node.js:355:11)
!!!
Error
at C:/MyProject/src/server/controllers/bookingController.js:81:19
at tryCatcher (C:\MyProject\request-promise\node_modules\bluebird\js\main\util.js:26:23)
at Promise._settlePromiseFromHandler (C:\MyProject\request-promise\node_modules\bluebird\js\main\promise.js:510:31)
at Promise._settlePromiseAt (C:\MyProject\request-promise\node_modules\bluebird\js\main\promise.js:584:18)
at Promise._settlePromises (C:\MyProject\request-promise\node_modules\bluebird\js\main\promise.js:700:14)
at Async._drainQueue (C:\MyProject\request-promise\node_modules\bluebird\js\main\async.js:123:16)
at Async._drainQueues (C:\MyProject\request-promise\node_modules\bluebird\js\main\async.js:133:10)
at Immediate.Async.drainQueues [as _onImmediate] (C:\MyProject\request-promise\node_modules\bluebird\js\main\async.js:15:14)
at processImmediate [as _immediateCallback] (timers.js:367:17)
如您所见,&#39;新错误()&#39;提供有关调用堆栈的更多有用信息,因为它有
&#39; C:/MyProject/src/server/controllers/bookingController.js'
我猜这是因为“错误”。异常是使用上一个刻度创建的,因此它的堆栈跟踪与我的&#39; bookingController.js&#39;无关。无论如何。
另外,我看到了“请求承诺”#39;内部使用&#; bluebird&#39;,所以从技术上讲,我可以使用Promise.longStackTraces()。
最后,我的问题是:除了使用&#39; new Error()之外,还有更聪明的方法来获得正确的堆栈跟踪.stack&#39;诀窍,因为Promise.longStackTraces()的生产过于繁重?
答案 0 :(得分:1)
嗯,nodejs提供了一种更漂亮的方法来捕获nodeJS上的实际堆栈,这符合我的需求:
let capturedStack = {};
Error.captureStackTrace(capturedStack, writeStack);
console.log(capturedStack.stack);