【问题标题】:Using promises - Logging stack trace in fail handler使用承诺 - 在失败处理程序中记录堆栈跟踪
【发布时间】:2013-03-29 16:21:25
【问题描述】:

我对 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 失败处理程序中访问堆栈跟踪?

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

【问题讨论】:

  • 不能在javascript中构建trace并将其输出到客户端而不是在服务器上查看吗?
  • 如何在 javascript 中构建跟踪?我更愿意将错误写入日志文件,而不是向网站访问者显示它们。

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


【解决方案1】:

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

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

【讨论】:

  • 谢谢马吕斯。为什么这不在 q 文档中?它在文档中,我只是错过了它吗?他们给出的例子应该清楚地表明这一点。
  • Cheeso 是纯 JavaScript,与 Q 无关。
  • 嗯,就我而言,它肯定与Q有关。fail方法是Q的接口,对吧?如果失败,它会被 Q 调用,对吗? Q 是否不想记录它正在发送的内容以及失败处理程序方法如何使用它?这似乎是文档中示例的明显候选者。
  • 更多的是关于“如何访问 JavaScript 错误对象的堆栈跟踪”。 Q.fail 不会以任何方式改变错误对象,它只是按照文档中的第一个参数传递它。
  • 使用源映射执行 err.stack 时,它显示的是 .js 文件,而不是源文件。是否有另一种方法可以让浏览器写出源文件?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-06
  • 2017-10-29
  • 2020-02-28
  • 2014-11-01
  • 1970-01-01
  • 2010-12-29
相关资源
最近更新 更多