使用承诺 - 在失败处理程序中记录堆栈跟踪 [英] Using promises - Logging stack trace in fail handler

查看:49
本文介绍了使用承诺 - 在失败处理程序中记录堆栈跟踪的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

控制台的输出:

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

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

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

所以我想我的问题是:

如何在 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);

这篇关于使用承诺 - 在失败处理程序中记录堆栈跟踪的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆