简体   繁体   English

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

[英]Using promises - Logging stack trace in fail handler

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? 如何在promise失败处理程序中访问堆栈跟踪?

EDIT : Any tips on how to improve the explanation are welcome, of course. 编辑 :当然,欢迎任何有关如何改进解释的提示。 If I didn't make myself clear, please let me know. 如果我不清楚,请告诉我。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM