web-dev-qa-db-ja.com

promiseの使用-フェイルハンドラーでスタックトレースをログに記録する

私は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フェイルハンドラーでスタックトレースにアクセスするにはどうすればよいですか?

[〜#〜] edit [〜#〜]:もちろん、説明を改善するためのヒントは大歓迎です。はっきりしなかった場合はお知らせください。

31
dave

エラーオブジェクトをログに記録しても、エラーのスタックトレースは出力されません。あなたはそれを具体的に求める必要があります:

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