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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15691366/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 01:43:17  来源:igfitidea点击:

Using promises - Logging stack trace in fail handler

javascriptnode.jsstack-tracepromiseq

提问by dave

I am rather new to nodejs so I will explain in a bit more detail what I am trying to do.

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

I have a webserver. If a request fails I want to log the stack trace of that exception, but deliver a error page and not crash the server.

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

As an example, the function handling the requests:

例如,处理请求的函数:

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();

The console's output:

控制台的输出:

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

I can't see a way to access the stack trace. But when I throw an exception in the .fail-handler (or just omit the complete .fail-handler), I get a stack trace on the console (but I'd have to restart the server).

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

So I guess my question is:

所以我想我的问题是:

How do I access the stack trace in a promise fail handler?

如何访问承诺失败处理程序中的堆栈跟踪?

EDIT: Any tips on how to improve the explanation are welcome, of course. If I didn't make myself clear, please let me know.

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

回答by Mariusz Nowak

Logging the error object won't print error's stack trace. You need to ask for it specifically:

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

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