使用promises - 在失败处理程序中记录堆栈跟踪

时间:2013-03-28 20:17:32

标签: javascript node.js stack-trace promise q

我对nodejs比较陌生,所以我会更详细地解释一下我想要做什么。

我有一个网络服务器。如果请求失败,我想记录该异常的堆栈跟踪,但是提供错误页面而不是使服务器崩溃。

例如,处理请求的函数:

var Q = require('q');

var requestHandler = function () {
    // Here I get the data etc. that was requested. As this is not important, just a dummy here
    Q.resolve()
        // Now I answer the request
        .then(function (data) {
            // Dummy Code representing the sending of a response
            console.log('sending response …');
            console.log('oh no! an exception');
            // Now an Exception occurs
            throw new Error('You did something wrong!');
        })
        // If there was any error, show the error page instead
        .fail(function (err) {
            // Dummy Code representing the sending of the error page
            console.log('sending error page');
            // Additionally I want to write the error into a log file
            console.error('You had an error: ', err);
        })
        // If there was an error in the .fail-handler, I deserve the server to crash
        .done();
};

// A request comes in, I want to call my handler
requestHandler();

控制台的输出:

sending response …
oh no! an exception
sending error page
You had an error:  [Error: You did something wrong!]

我看不到访问堆栈跟踪的方法。但是当我在.fail-handler中抛出异常(或者只是省略完整的.fail-handler)时,我在控制台上获得了一个堆栈跟踪(但我必须重新启动服务器)。

所以我想我的问题是:

如何在promise失败处理程序中访问堆栈跟踪?

编辑:欢迎任何有关如何改进说明的提示,当然。如果我没有说清楚,请告诉我。

1 个答案:

答案 0 :(得分:50)

记录错误对象不会打印错误的堆栈跟踪。 你需要具体要求:

console.error('You had an error: ', err.stack);